首页 > 解决方案 > 我想从用户使用 jquery 填写的表单输入中动态更改按钮的值

问题描述

用户填写表单(自定义产品),我想利用他们的输出动态更改按钮的信息。

我已成功获取用户填写表单的内容,但无法成功更改按钮中的值。

我的表格:

<form>
    <fieldset>
        <legend>Selecting elements</legend>
        <p>
            <label>Select type : </label>
            <select id="type" name="type">
                <option> X </option>
                <option> Palleitte </option>
            </select>
        </p>
    </fieldset>
</form>

我的按钮:

<button name="julien" class="snipcart-add-item" id="my-button"
        data-item-id="{{ product.identifier }}"
        data-item-name="{{ product.name }}"
        data-item-price="20.00"
        data-item-custom2-name="Type"
        data-item-custom2-options="Cachet|Palleitte"
        data-item-custom2-value=""
        data-item-custom3-name="Quantité"
        data-item-custom3-options="100g|200g|500g|1kg|100kg"
        data-item-custom3-value="500g">
    ADD TO THE CART 
</button>

我的 jQuery 代码:

$('#weight').change(function() {
    $('#my-button').data('item-custom3-value', $(this).val());
    console.log($('#my-button').data('item-custom3-value', $(this).val()));
    console.log($(this).val());
});

我希望更改按钮data-item-custom2-value=""的值:通过用户填写表单的值,提前致谢!

标签: jqueryhtmlformsbutton

解决方案


要更改以使其工作的代码行:

    console.log($('#my-button').attr('data-item-custom3-value', $(this).val()));

更一般的答案:

    console.log($('#id-you-target').attr('element-you-want-to-target', $(this).val()));

希望它会帮助你!


推荐阅读