开发者

How to find the submit button in a specific form in jQuery

I try to get jQuery object of a submit button in a specific form (there are several forms on the same page).

I managed to get the form element itself. It looks something like this:

var curForm = curElement.parents("form");

The开发者_运维知识库 current Element has the context HTMLInputElement. The several techniques I tried to get the according submit element of the form:

var curSubmit = curForm.find("input[type='submit']");
var curSubmit = $(curForm).find("input[type='submit']");    
var curSubmit = curForm.find(":submit");
var curSubmit = $(curForm).find(":submit");    
var curSubmit = $(curSubmit, "input[type='submit']");

the result is always the same (and very strange). The result that I get is the same element as "curElement".

So how can I get the right submit button?


The following should work:

var submit = curElement.closest('form').find(':submit');


This should work:

var curSubmit = $("input[type=submit]",curForm);

EDIT: Note the missing ' in the selector


Using plain javascript (without relying on jquery):

var curSubmit = curForm.querySelector('button[type="submit"]');


This works for me:

var curSubmit = $("input[type=submit]",this);

where this mean current form submitted

for ex. to get the name of submitted button and all inputs submitted

$( "form" ).on( "submit", function( event ) {
    event.preventDefault();
    var data = $(this).serialize(); //all input variables  
    console.log(data); //print data in console
    var submit = $("input[type=submit]",this).attr('name'); 
    alert(submit); // name of submit button
});


Because a HTML5 submit button may be out of form tag http://www.w3.org/TR/html-markup/input.submit.html#input.submit.attrs.form, you can use the following code to find it:

$(curElement.closest('form').get(0).elements).filter(':submit')


In case you want to find the submit button of the form after it was submitted, you may find the following useful ... I use it to disable the submit button after the form was submitted to prevent multiple clicks.

$("form").submit(function () {
  if ($(this).valid()) { // in case you have some validation
    $(this).find(":submit").prop('disabled', true);
    $("*").css("cursor", "wait"); // in case you want to show a waiting cursor after submit
  }
});


BTW: Last selector looks weird. It selects each curSubmit(hm?) in every input[type=submit] tag. May be you mean var curSubmit = $("input[type=submit]", curForm);

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜