Jquery gets form id by input id

I have a really basic question. How can I get the form id using the input element id.

<form id="my_form"> <fieldset> <!--some <div>'s--> <input id="my_input"></div> <!--some <div> end--> </fieldset> </form> 

Now if i have

 var form_input = $('#my_input'); 

How can I get id "my_form"?

Thanks.

+6
jquery forms
source share
3 answers

Use closest . He searches for the ancestors * of the element to find the first (closest) match.

 $('#my_input').closest('form').attr('id'); 

* Note: the closest () is looking up starting from the current item, so it can match the current item.

+20
source share

You don't even need jQuery. Each form element has a .form attribute that can be used to directly access the form object without the need for an iterative jQuery search:

 $('#my_input').get(0).form.id 
+8
source share

The easiest way is to use closest() :

 var id = $('#my_input').closest('form').attr('id'); 
+4
source share

All Articles