How to get the form parent of an input?

0 votes
asked Jun 13, 2009 by ropstah

I need to get a reference to the FORM parent of an INPUT when I only have a reference to that INPUT. Is this possible with JavaScript? Use jQuery if you like.

function doSomething(element) {
    //element is input object
    //how to get reference to form?
}

This doesn't work:

var form = $(element).parents('form:first');

alert($(form).attr("name"));

9 Answers

0 votes
answered Jun 13, 2009 by paolo-bergantino

Native DOM elements that are inputs also have a form attribute that points to the form they belong to:

var form = element.form;
alert($(form).attr('name'));

According to w3schools, the .form property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.

If this were a different type of element (not an <input>), you could find the closest parent with closest:

var $form = $(element).closest('form');
alert($form.attr('name'));

Also, see this MDN link on the form property of HTMLInputElement:

0 votes
answered Jun 13, 2009 by yfeldblum

Using jQuery:

function doSomething(element) {
    var form = $(element).closest("form").get().
    //do something with the form.
}
0 votes
answered Jun 13, 2009 by gareth

Every input has a form property which points to the form the input belongs to, so simply:

function doSomething(element) {
  var form = element.form;
}
0 votes
answered Jun 19, 2010 by nikov

I needed to use element.attr('form') instead of element.form

I use firefox on Fedora 12

0 votes
answered Jun 4, 2011 by steven-wright

If using jQuery and have a handle to any form element, you need to get(0) the element before using .form

var my_form = $('input[name=first_name]').get(0).form;
0 votes
answered Jun 23, 2012 by nigel-francois

I use a bit of jQuery and old style javascript - less code

$($(this)[0].form) 

This is a complete reference to the form containing the element

0 votes
answered Jun 4, 2014 by josh-p

would this work? (leaving action blank submits form back to itself too, right?)

<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>

"this" would be the select element, .form would be its parent form. Right?

0 votes
answered Jun 25, 2015 by sadnix

simply as:

alert( $(this.form).attr('name') );
0 votes
answered Jun 16, 2016 by jadeye

And one more....

var _e = $(e.target); // e being the event triggered
var element = _e.parent(); // the element the event was triggered on
console.log("_E " + element.context); // [object HTMLInputElement]
console.log("_E FORM " + element.context.form); // [object HTMLFormElement]
console.log("_E FORM " + element.context.form.id); // form id
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...