点击后使用javascript更改按钮的文本

时间:2016-07-08 19:51:35

标签: javascript php jquery html forms

我是javascript的新手,我遇到代码问题:

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<form id="add-to-cart-form">
    <div class="cart">
        <input type="hidden" name="product_code" value="prince"/>
        <input type="text" name="name" value="First Form"/>
        <button id="btn_add" type="submit">Add to Cart</button>
    </div>
</form>

<form id="add-to-cart-form">
    <div class="cart">
        <input type="hidden" name="product_code" value="lionel"/>
        <input type="text" name="name" value="Second Form"/>
        <button id="btn_add" type="submit">Add to Cart</button>
    </div>
</form>

   
<script>
    $(document).ready(function(){
        $("#add-to-cart-form").submit(function(e) {

            $("#btn_add").html('Good');
            $("input[name='name']").val('Input change');

            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    });
</script>

我的代码的目的是在提交表单时更改提交按钮并更改提交表单输入的value。但是使用我的代码,在提交第一个表单后,提交按钮会改变(这是正常的),第二个表单的输入字段的值会改变(不正常)。提交第二张表格后,它根本不起作用。

抱歉,我尽力使帖子清晰明了。我不是母语为英语的人。

1 个答案:

答案 0 :(得分:1)

每页的ID应该是唯一的
试试吧:

<form id="add-to-cart-form-first">
    <div class="cart">
        <input type="hidden" name="product_code" value="prince"/>
        <input type="text" name="name" value="First Form"/>
        <button id="btn_add_first" type="submit">Add to Cart</button>
    </div>
</form>

<form id="add-to-cart-form-second">
    <div class="cart">
        <input type="hidden" name="product_code" value="lionel"/>
        <input type="text" name="name" value="Second Form"/>
        <button id="btn_add_second" type="submit">Add to Cart</button>
    </div>
</form>


<script>
    $(document).ready(function(){
        $("form").submit(function(e) {

            $(this).find("[type=submit]").html('Good');
            $(this).find("input[name='name']").val('Input change');

            e.preventDefault(); // avoid to execute the actual submit of the form.
        });
    });
</script>