Mikk
Mikk

Reputation: 2229

jquery get form id by input id

I have really basic question. How can I get form id by input element id.

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

Now if I have

var form_input = $('#my_input');

How can I get id "my_form"?

Thank you.

Upvotes: 7

Views: 48980

Answers (3)

nickf
nickf

Reputation: 546035

Use closest. It searches up the ancestors* of an element to find the first (closest) match.

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

*Note: closest() searches upwards starting with the current element, therefore it can match the current element.

Upvotes: 20

Gareth
Gareth

Reputation: 138042

You don't even need jQuery for this. Every form element has a .form attribute you can use to directly access the form object without needing jQuery's iterative search:

$('#my_input').get(0).form.id

Upvotes: 9

cletus
cletus

Reputation: 625057

The simplest method is to use closest():

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

Upvotes: 4

Related Questions