jQuery:如何获取表单提交时点击了哪个按钮? [英] jQuery: how to get which button was clicked upon form submission?
问题描述
我为表单提交设置了一个 .submit()
事件.我在页面上也有多个表单,但在这个例子中只有一个.我想知道点击了哪个提交按钮而不对每个按钮应用 .click()
事件.
I have a .submit()
event set up for form submission. I also have multiple forms on the page, but just one here for this example. I'd like to know which submit button was clicked without applying a .click()
event to each one.
设置如下:
<html>
<head>
<title>jQuery research: forms</title>
<script type='text/javascript' src='../jquery-1.5.2.min.js'></script>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('form[name="testform"]').submit( function(event){ process_form_submission(event); } );
});
function process_form_submission( event ) {
event.preventDefault();
//var target = $(event.target);
var me = event.currentTarget;
var data = me.data.value;
var which_button = '?'; // <-- this is what I want to know
alert( 'data: ' + data + ', button: ' + which_button );
}
</script>
</head>
<body>
<h2>Here's my form:</h2>
<form action='nothing' method='post' name='testform'>
<input type='hidden' name='data' value='blahdatayadda' />
<input type='submit' name='name1' value='value1' />
<input type='submit' name='name2' value='value2' />
</form>
</body>
</html>
除了在每个按钮上应用 .click() 事件之外,还有没有办法确定点击了哪个提交按钮?
Besides applying a .click() event on each button, is there a way to determine which submit button was clicked?
推荐答案
我问了同样的问题:如何从表单提交事件中获取导致提交的按钮?
我最终想出了这个解决方案,而且效果很好:
I ended up coming up with this solution and it worked pretty well:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val();
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
<小时>
如果你有多个表单,你可能需要稍微调整一下,但它应该仍然适用
In your case with multiple forms you may need to tweak this a bit but it should still apply
这篇关于jQuery:如何获取表单提交时点击了哪个按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!