简体   繁体   中英

How do I handle Two Submit buttons on One Form?

I have two submit buttons and one form. How do I check what submit button was selected in my jquery code?

<% 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;
        //});
    });
});
$('#submitHome').click(function() {
      //navigate to Home;
});
$('#submitNext').click(function() {
      return true;
});

These should work if you pull them outside of the form.submit(). (right now those handlers are being attached after the form is submitted, which is too late since the click has already occurred)

You can try something like this

$(function() {
 var buttonpressed;
 $('input[type=submit]').click(function() {
      buttonpressed = $(this).attr('name')
 })
 $('form').submit(function() {
      alert('button clicked was ' + buttonpressed)
        buttonpressed=''
    return(false)
 })
})

Source: https://forum.jquery.com/topic/determining-which-of-two-submit-buttons-were-clicked-in-a-single-form

This should work:

<% 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;
  });
});
$(function(){
  $(".submitButton").click(function(e){
    alert($(this).attr("name"));
  });
});​

Working demo behind the link.

Create two action methods and that handles two post seperately that takes formcollection as param. Add two input with type=button and bind the click event with $.post to your action method with values from the form controls you need for that post.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM