enigma
enigma

Reputation: 82

how can I check which submit button was pressed?

I have a two submit buttons set up for form submission. I'd like to know which submit button was clicked without applying a .click() event to each one. One more thing I am using ASP.NET MVC 3 and want to get the clicked button name in Controller.

Here's the setup:

<a class="anchorbutton">
  <input  type="submit" value="Save" id="Save" class="hrbutton"/>
</a>
<input  type="submit" value="Save & Next" id="SaveNext" class="hrbutton  anchorbutton"/>           


 $('#form').live('submit', function (e)    
{      
    e.preventDefault();
    var form = $('#form');      
    $.ajax({
        cache: false,
        async: true,
        type: "POST",
        url: form.attr('action'),
        data: form.serialize(),
        success: function (data) {
            $.ajax({
                url: 'url',
                dataType: "html",
                success: function (data) {
                    $("#div").html(data);                     

                }
            });
        }
    });
    return false;
});


[HttpPost]
public JsonResult Post(FormCollection form, string submitButton)
{         

}

Upvotes: 1

Views: 1634

Answers (3)

Rafay
Rafay

Reputation: 31033

well try binding the click event handler to the Save and SaveAndNext buttons like

$(document).delegate("#Save,#SaveAndNext","click",function(e){
 console.log($(this).attr("id"));//here you will know which button was pressed
 //next you can check if the form is valid or not
 if($(this).closest('form').valid()){
 //form is valid submit it ajax(ily)

 }else{
 //form is not valid
 }
});

you can also cache the selector

var $this = $(this);

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Give your buttons names:

<a class="anchorbutton">
    <button type="submit" name="save" id="Save" class="hrbutton">Save</button>
</a>
<button type="submit" name="savenext" id="SaveNext" class="hrbutton anchorbutton">Save & Next</button>

and then your controller action could take those parameters with the same name and check if it has a value:

[HttpPost]
public ActionResult Post(string save, string saveNext, FormCollection form)
{
    if (!string.IsNullOrEmpty(save))
    {
        // The Save button was clicked
    }
    else if (!string.IsNullOrEmpty(saveNext))
    {
        // The Save & Next button was clicked
    }
    else
    {
        // None of the submit buttons were used or clicked to submit the form.
        // The user simply pressed the Enter key while the focus was inside
        // some of the input fields of the form
    }

    ...
}

Oh and by the way, the .live jQuery function is deprecated. Use .on instead.

Upvotes: 2

Aravind
Aravind

Reputation: 1549

Try

    ButtonClick Event " OnClick="MyButton_Click" "

Upvotes: 0

Related Questions