开发者

jquery get form id by input id

开发者 https://www.devze.com 2022-12-24 17:45 出处:网络
I have really basic question. How can I get form id by input element id. <form id=\"my_form\"> <fieldset>

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');开发者_StackOverflow

How can I get id "my_form"?

Thank you.


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.


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


The simplest method is to use closest():

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

精彩评论

暂无评论...
验证码 换一张
取 消