views:

3412

answers:

5

Hi,

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 (or else jQuery) ?

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  A: 

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 was 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'));
Paolo Bergantino
Alright this works.. About the form attribute. I just tried it and that also works. But this isn't supported across browsers you're saying?
Ropstah
I'm pretty sure it is. I'm just not 100% sure so I don't want to promise anything. I'm looking into it right now...
Paolo Bergantino
Use element.form - it will work on more browsers than jQuery does. It's also one property reference, so will be around a thousand times more efficient than walking up the DOM tree with closest().
NickFitz
I agree. As I said, I just wasn't initially sure if the form property was extensively implemented in all common browsers. I've edited my answer to more explicitly list this as the better option while I'm leaving closest as a tidbit if this was a different type of element.
Paolo Bergantino
+1  A: 

Using jQuery:

function doSomething(element) {
    var form = $(element).closest("form").get().
    //do something with the form.
}
Justice
+6  A: 

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

function doSomething(element) {
  var form = element.form;
}
Gareth
this doesn't work somehow..?
Ropstah
A: 

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

I use firefox on Fedora 12

Nikov
A: 

Hi Paolo Bergantino,

It does not work on change event.

Sohail