Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discover which form button triggered submission

In my form, I have two submit buttons.

<input type="submit" name="save" value="Save as draft"/>
<input type="submit" name="send" value="Start sending" />

Now before submitting the form back to the server, I want to perform specific tasks depending on which button was clicked.

$('form').submit(function(){
    if submit equals save
       task 1;
    elseif submit equals send
       task 2               
}

How do I check which button was pressed?

like image 581
goh Avatar asked May 11 '11 16:05

goh


2 Answers

$(":submit").click(function() {
    $("form").data("submit-button", this.name);
});

$("form").submit(function() {
    var button = $(this).data("submit-button");
    ...
});

Add a click handler on your submit buttons that stores the name. Then extract that name in your submit handler.

like image 53
Raynos Avatar answered Sep 22 '22 05:09

Raynos


If it were me I would do this a little bit differently. I would do something along the lines of -

<button type='button' id='formSave'>Save as draft</button>
<button type='button' id='formSend'>Start Sending</button>

$('#formSave').click(function(){
    //submit form
    //task 1
});

$('#formSend').click(function(){
    //submit form
    //task 2
});

Im just basing my answer off of your button names and whatnot but it sounds like you want to do something simliar to this.

like image 25
HurnsMobile Avatar answered Sep 20 '22 05:09

HurnsMobile