开发者

Value of submit button clicked

This should be really straight forward.

I'm checking if a form is being submitted using jquery. The form has multiple submit buttons with various values:

<button type="submit" value="foo">Foo</button>
开发者_Python百科<button type="submit" value="bar">Bar</button>

I would like to find the value of the button that just submitted the form:

$(form).live('submit', function() {
    // Get value of submit button
}

Thanks


Bind the event to submit buttons instead of the form and then $(this) would have the reference to the buttons...

$(":submit").live('click', function() {
    alert($(this).val());
})

EDIT As of jQuery 1.7 live is deprecated. Use on instead.

$(document).on("click", ":submit", function(e){
    alert($(this).val());
});


This seems to get the clicked submit button:

jQuery("#TheForm").context.activeElement.name
jQuery("#TheForm").context.activeElement.value


You can't if you're using the "submit" event. A form can be submitted without ever hitting a submit button.

In order to obtain which button was clicked, you need to alter your approach by using custom events and marking down which button was actually clicked (creating a selector that can catch click on any of the X buttons in the form). That also requires binding a custom event and prohibiting submit event of the form itself.


$('input[type="submit"]').click(function() {
    alert ($(this).val());
}


I ended up using the click event on each submit button, as others have suggested. That works fine, and you can return false from them if you want to cancel the submit. Just don't try to also bind the submit event of the form. You could also have each of these handlers call a common submit-handler function, passing their own value as an argument.


I recommend the use of the Firebug Add On, you get a lot of responses to your questions just looking to the data in the console. I realize that in your case you can access the submit value this way:

alert($(this).context.submit.value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜