How to handle two submit buttons in one form?

I have two submit buttons and one form. How to check which 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;
        //});
    });
});
+5
source share
5 answers
$('#submitHome').click(function() {
      //navigate to Home;
});
$('#submitNext').click(function() {
      return true;
});

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

+16
source

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

+4
source

:

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

.

+1

Create two action methods and process the two columns separately, which take the formcollection as param. Add two inputs using the type = button and attach the click event with $ .post to your action method with the values ​​from the form controls that you need for this post.

0
source

All Articles