如何检测在jquery中单击了哪个提交按钮

时间:2013-03-20 23:33:23

标签: jquery submit

如果我的表单上有2个提交按钮,是否可以在jquery中检测哪个被点击

<input name="submit" type="submit" value="Button 1">
<input name="submit" type="submit" value="Button 2">

这一直是“按钮1”

alert($("input[name=submit]").val());

3 个答案:

答案 0 :(得分:2)

您不一定需要使用提供的HTML的唯一ID:

$("input[type=submit]").click(function() {
   alert($(this).val());
});

编辑:我同意您应该通过其中一个按钮更改名称

答案 1 :(得分:0)

您需要拥有唯一ID:

<input id="submit1" name="submit" type="submit" value="Button 1">
<input id="submit1" name="submit" type="submit" value="Button 2">
  

id属性指定HTML元素的唯一ID(该值在HTML文档中必须是唯一的。)

http://www.w3schools.com/tags/att_global_id.asp

答案 2 :(得分:0)

最好的选择是为每个按钮添加唯一ID,您可以这样做:

$('input').on('click', function(){
    alert(this.id);
});

否则,如果您想保留当前结构并返回您需要的值:

$('input').on('click', function(){
    // the value inside attr() can be any property of the element
    alert($(this).attr('value'));
});