【问题标题】:How do I handle Two Submit buttons on One Form?如何处理一个表单上的两个提交按钮?
【发布时间】:2011-03-20 07:01:31
【问题描述】:

我有两个提交按钮和一个表单。如何检查在我的 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;
        //});
    });
});

【问题讨论】:

  • 这个老问题有帮助吗? stackoverflow.com/questions/2154039/…
  • 你应该使用按钮而不是提交输入。
  • 你为什么要删除你的last question
  • @BalusC - 这是一个没有答案的问题,基于我正在尝试做的事情。我不想让它混淆。对不起:(

标签: javascript jquery html asp.net-mvc


【解决方案1】:
$('#submitHome').click(function() {
      //navigate to Home;
});
$('#submitNext').click(function() {
      return true;
});

如果您将它们拉到 form.submit() 之外,这些应该可以工作。 (现在这些处理程序是在提交表单后附加的,因为点击已经发生,所以为时已晚)

【讨论】:

  • 如果用户使用键盘提交,这不起作用
【解决方案2】:

你可以试试这样的

$(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

【讨论】:

  • 如果用户使用键盘提交,这是行不通的。
【解决方案3】:
$(function(){
  $(".submitButton").click(function(e){
    alert($(this).attr("name"));
  });
});​

Working demo behind the link.

【讨论】:

    【解决方案4】:

    这应该可行:

    <% 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;
      });
    });
    

    【讨论】:

      【解决方案5】:

      创建两个动作方法,分别处理两个以formcollection为参数的post。 使用 type=button 添加两个输入,并使用 $.post 将 click 事件绑定到您的操作方法,并使用该帖子所需的表单控件中的值。

      【讨论】:

        猜你喜欢
        • 2019-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多