[jquery] jQuery find parent form

i have this html

<ul>
    <li><form action="#" name="formName"></li>
    <li><input type="text" name="someName" /></li>
    <li><input type="text" name="someOtherName" /></li>
    <li><input type="submit" name="submitButton" value="send"></li>
    <li></form></li>
</ul>

How can i select the form that the input[name="submitButton"] is part of ? (when i click on the submit button i want to select the form and append some fields in it)

This question is related to jquery traversal

The answer is


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
});

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.


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) : $();

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`
});