如何处理一个表单上的两个提交按钮?
问题描述:
我有两个提交按钮和一个表单。我如何检查在我的jQuery代码中选择了哪个提交按钮?如何处理一个表单上的两个提交按钮?
<% using (Html.BeginForm("UserInfo", "Home", FormMethod.Post, new { id = "formNext" })) { %>
....
<input id="submitHome" type="submit" name="goHome" value="Home" />
<input id="submitNext" type="submit" name="getNext" value="Next" />
<% } %>
$(document).ready(function() {
$('#formNext').submit(function() {
//Code Does not work but looking at something like this...
//$('#submitHome').click(function() {
// navigate to Home;
//});
//$('#submitNext').click(function() {
// return true;
//});
});
});
答
$(function(){
$(".submitButton").click(function(e){
alert($(this).attr("name"));
});
});
+0
演示不起作用... – 2010-07-23 19:52:52
答
这应该工作:
<% using (Html.BeginForm("UserInfo", "Home", FormMethod.Post, new { id = "formNext" })) { %>
....
<input id="submitHome" type="submit" name="goHome" value="Home" />
<input id="submitNext" type="submit" name="getNext" value="Next" />
<% } %>
$(document).ready(function() {
$('#submitHome').click(function(e) {
e.preventDefault(); // prevent the page to do the usuall onclick event (from reloading the page)
// navigate to Home;
});
$('#submitNext').click(function(e) {
e.preventDefault();
// return true;
});
});
答
创建两个行动的方法和seperately处理两个岗位将formcollection作为参数。 使用type =按钮添加两个输入,并使用$ .post将click事件绑定到您的操作方法,并使用该帖子所需的表单控件中的值。
答
你可以尝试这样的事情
$(function() {
var buttonpressed;
$('input[type=submit]').click(function() {
buttonpressed = $(this).attr('name')
})
$('form').submit(function() {
alert('button clicked was ' + buttonpressed)
buttonpressed=''
return(false)
})
})
来源:https://forum.jquery.com/topic/determining-which-of-two-submit-buttons-were-clicked-in-a-single-form
这是否老问题帮帮忙? http://stackoverflow.com/questions/2154039/jquery-submit-how-can-i-know-what-submit-button-was-pressed – Tobiasopdenbrouw 2010-07-23 19:18:01
你应该使用按钮,而不是提交输入。 – recursive 2010-07-23 19:33:46
为什么你删除你的[最后一个问题](http://stackoverflow.com/questions/3366104/compatibility-view-kills-my-style-sheet-what-to-do)? – BalusC 2010-07-29 19:32:40