获取提交表单的ID

时间:2016-09-13 12:29:47

标签: javascript forms

I posted a question earlier动态创建表单,并得到了很好的建议。目前我有一个表单列表,formCELL,每个表单创建如下。

html

<div class="container">
    <div class="container-element" id="1">
        <h3>HEADER</h3>
        <form action="refresh.php" id="formCELL" method="post" name="form_1">
            <div class="panel-body">
                <div class="col-xs-10 com">
                    CONTENT GOES HERE
                </div>
                <div class="col-xs-2 btn">
                    <button class="btn btn-primary" id="refresh" type="submit">Refresh</button>
                </div>
            </div>
        </form>
    </div>
    <div class="container-element" id="2">
        <h3>HEADER</h3>
        <form action="refresh.php" id="formCELL" method="post" name="form_2">
            <div class="panel-body">
                <div class="col-xs-10 com">
                    CONTENT GOES HERE
                </div>
                <div class="col-xs-2 btn">
                    <button class="btn btn-primary" id="refresh" type="submit">Refresh</button>
                </div>
            </div>
        </form>
    </div>
    <div class="container-element" id="3">
        <h3>HEADER</h3>
        <form action="refresh.php" id="formCELL" method="post" name="form_3">
            <div class="panel-body">
                <div class="col-xs-10 com">
                    CONTENT GOES HERE
                </div>
                <div class="col-xs-2 btn">
                    <button class="btn btn-primary" id="refresh" type="submit">Refresh</button>
                </div>
            </div>
        </form>
    </div>
    <div class="container-element" id="4">
        <h3>HEADER</h3>
        <form action="refresh.php" id="formCELL" method="post" name="form_4">
            <div class="panel-body">
                <div class="col-xs-10 com">
                    CONTENT GOES HERE
                </div>
                <div class="col-xs-2 btn">
                    <button class="btn btn-primary" id="refresh" type="submit">Refresh</button>
                </div>
            </div>
        </form>
    </div>
</div>

的javascript

$(document).ready(function() {

   $('#formMAIN').submit(function(event) {

       //formCELL is generated here through AJAX call.....

   });
});

$('#formCELL').submit(function(event) {

    // process the form
    alert("about to submit");
    //AJAX call to go here

    var user_id = $(this).closest("form").attr('id');   
    alert(user_id);

    event.preventDefault();
});

我正在尝试获取正在提交的表单的ID,以便我可以进一步处理它,并且我尝试了不同的$(this).closest(&#34; form&#34;)。attr (&#39; ID&#39);并且都返回 undefined

的值

如何获取提交表单的ID?

3 个答案:

答案 0 :(得分:1)

您可以使用event.target.id获取表单ID

答案 1 :(得分:0)

只需将“submit”事件绑定到整个表单,然后使用

$(this).attr('id');

答案 2 :(得分:0)

也许使用data-id兄弟。 将data-id作为属性放在表单中 所以你可以很容易地使用它 $(本).attr( '数据-ID')