使用onsubmit事件获取提交按钮的ID

时间:2014-02-05 12:42:12

标签: jquery forms onsubmit

HTML:

<form action="javascript:void(0)" method="post" onsubmit="form_process()">


<input type="submit" id="btn_id" value="Submit" />
</form>

javascript片段:

function form_process(){


    $elem = $(this);

    if(window.console){

    console.log(" button id = " + $elem.attr('id'));


    }



}// end if function form_process()

但是控制台会将id显示为undefined。问题是在jQuery中选择提交按钮。如何获取提交按钮的id

2 个答案:

答案 0 :(得分:0)

在您的代码this中引用全局窗口对象。这类似于$(window)

选项1:

在表单中传递this

<form action="javascript:void(0)" method="post" 
         id="my-form" onsubmit="form_process(this)">

function form_process(obj){    

    $elem = $(obj).find(input[type="submit"]);
    if(window.console){
      console.log(" button id = " + $elem.attr('id'));
    }

}

选项2:不引人注目的JS

$('#my-form').submit(function(){
  $elem = $(this);
});

答案 1 :(得分:0)

您可以使用以下结构;

<强> HTML:

<form action="javascript:void(0)" method="post">
     <input type="submit" id="btn_id" value="Submit" />
</form>

<强> JS:

// or you can use class for this form
$('form').on('submit', function() {
     $elem = $(this);
     var id = $elem.children('input[type="submit"]').attr('id');
     if(window.console){
         console.log(" button id = " + id);
     }

});

这是一个工作小提琴: http://jsfiddle.net/cubuzoa/qWvz9/1/