Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery get form id by input id

Tags:

jquery

forms

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.

like image 756
Mikk Avatar asked Mar 28 '10 12:03

Mikk


People also ask

How to get the form id in jQuery?

Try the following: var user_id = $(this). closest("form"). attr("id");

How do I find the ID of an input element?

Accessing Form Elements using getElementById In order to access the form element, we can use the method getElementById() like this: var name_element = document. getElementById('txt_name'); The getElementById() call returns the input element object with ID 'txt_name' .

How to get form id on button click in jQuery?

getElementById(form). submit(); $(this). dialog("close"); } } }); });


2 Answers

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.

like image 158
nickf Avatar answered Sep 23 '22 20:09

nickf


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
like image 40
Gareth Avatar answered Sep 21 '22 20:09

Gareth