jQuery find parent form

前端 未结 5 1757
名媛妹妹
名媛妹妹 2020-12-07 10:13

i have this html

相关标签:
5条回答
  • 2020-12-07 10:23

    To me, this looks like the simplest/fastest:

    $('form input[type=submit]').click(function() { // attach the listener to your button
       var yourWantedObjectIsHere = $(this.form);   // use the native JS object with `this`
    });
    
    0 讨论(0)
  • 2020-12-07 10:30

    As of HTML5 browsers one can use inputElement.form - the value of the attribute must be an id of a <form> element in the same document. More info on MDN.

    0 讨论(0)
  • 2020-12-07 10:39

    see also jquery/js -- How do I select the parent form based on which submit button is clicked?

    $('form#myform1').submit(function(e){
         e.preventDefault(); //Prevent the normal submission action
         var form = this;
         // ... Handle form submission
    });
    
    0 讨论(0)
  • 2020-12-07 10:40

    I would suggest using closest, which selects the closest matching parent element:

    $('input[name="submitButton"]').closest("form");
    

    Instead of filtering by the name, I would do this:

    $('input[type=submit]').closest("form");
    
    0 讨论(0)
  • 2020-12-07 10:43

    You can use the form reference which exists on all inputs, this is much faster than .closest() (5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.

    var input = $('input[type=submit]');
    var form = input.length > 0 ? $(input[0].form) : $();
    
    0 讨论(0)
提交回复
热议问题