Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
1
rated 0 times [  5] [ 4]  / answers: 1 / hits: 166978  / 15 Years ago, sat, june 13, 2009, 12:00:00

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

More From » jquery

 Answers
242

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:




[#99321] Tuesday, June 9, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
loganl

Total Points: 424
Total Questions: 86
Total Answers: 112

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
;