jQuery find parent form

JqueryTraversal

Jquery Problem Overview


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)

Jquery Solutions


Solution 1 - Jquery

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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.

Solution 5 - Jquery

see also https://stackoverflow.com/questions/311579/jquery-js-how-do-i-select-the-parent-form-based-on-which-submit-button-is-clic

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkmunkyView Question on Stackoverflow
Solution 1 - Jquerykarim79View Answer on Stackoverflow
Solution 2 - JquerypeterjwestView Answer on Stackoverflow
Solution 3 - JqueryuserfuserView Answer on Stackoverflow
Solution 4 - JqueryAlexander MihailovView Answer on Stackoverflow
Solution 5 - JqueryJonathan HendlerView Answer on Stackoverflow