在提交前点击。 JQuery的

时间:2016-06-03 13:31:10

标签: javascript jquery html forms

我要做的是更改<input>字段中的值。 这个想法是当客户点击表单内的3个按钮之一时 在提交到LIST_IDLIST_ID_12之前,3会更改,对应于点击的按钮。因此,当提交表单时,id将根据单击的按钮进行更改。

<input type="hidden" name="g" id="hidden_field" value="LIST_ID">

这是我尝试过的东西:

$('#subscription_form').submit(function() {
    jQuery(':button').click(function () {
        if (this.id == 'Button_1') {
            /*Action;*/
            $("#hidden_field").val("LIST_ID_1");    
        }
        else if (this.id == 'Button_2') {
            /*Action;*/
            $("#hidden_field").val("LIST_ID_2");
        }
        else if (this.id == 'Button_3') {
            /*Action;*/
            $("#hidden_field").val("LIST_ID_3");
        }
    });
});
<form action="//manage.kmail-lists.com/subscriptions/subscribe" method="POST" id="subscription_form" novalidate="novalidate" class="klaviyo_subscription_form">
    <input type="hidden" name="g" id="hidden_field" value="LIST_ID">
    <div class="klaviyo_fieldset">
        <div class="klaviyo_field_group">
            <label for="LIST_ID_$email">Email Address</label>
            <input type="email" id="LIST_ID_$email" name="email">
        </div>
    </div>
    <div class="klaviyo_form_actions">
        <button type="submit" id="Button_1" class="klaviyo_submit_button">
            <span>Button_1</span>
        </button>
        <button type="submit" id="Button_1" class="klaviyo_submit_button">
            <span>Button_2</span>
        </button>
        <button type="submit" id="Button_3" class="klaviyo_submit_button">
            <span>Button_3</span>
        </button>
    </div>
    <div class="klaviyo_below_submit"></div>
</form>

1 个答案:

答案 0 :(得分:1)

问题是您只在表单提交后附加了click事件。除非用户双击一个按钮(一次提交表单并附加点击处理程序,另一次实际触发点击处理程序),否则它将无效。您需要将click()处理程序放在submit()之外,如下所示:

$(':button').click(function() {
    if (this.id == 'Button_1') {
        $("#hidden_field").val("LIST_ID_1");    
    }
    else if (this.id == 'Button_2') {
        $("#hidden_field").val("LIST_ID_2");
    }
    else if (this.id == 'Button_3') {
        $("#hidden_field").val("LIST_ID_3");
    }
});

Working example

但是应该注意,最好挂钩submit()的{​​{1}}事件。在这种情况下,要获取单击的提交按钮,您需要使用form,如下所示:

document.activeElement

Working example

最后,您应该考虑使用DRY原则来使您的代码更短,更容易维护。要做到这一点,您可以在按钮上使用$('form').submit(function() { var $btn = $(document.activeElement); if ($btn.prop('id') == 'Button_1') { $("#hidden_field").val("LIST_ID_1"); } else if ($btn.prop('id') == 'Button_2') { $("#hidden_field").val("LIST_ID_2"); } else if ($btn.prop('id') == 'Button_3') { $("#hidden_field").val("LIST_ID_3"); } }); 属性,如下所示:

data-*
<button type="submit" id="Button_1" data-list="LIST_ID_1" class="klaviyo_submit_button">
    <span>Button_1</span>
</button>
<button type="submit" id="Button_2" data-list="LIST_ID_2" class="klaviyo_submit_button">
    <span>Button_2</span>
</button>
<button type="submit" id="Button_3" data-list="LIST_ID_3" class="klaviyo_submit_button">
    <span>Button_3</span>
</button>

Working example