How to detect which submit button is clicked in a

2019-08-04 15:48发布

问题:

If I have 2 submit buttons on a form:

<input name="submit" type="submit" value="Button 1">
<input name="submit" type="submit" value="Button 2">

I have this jquery but every time I click button 2 I get the alert for button 1.

$('form.profile').submit(function() {
if ($("input[type=submit]").val() == 'Button 1')
{
alert('you clicked button 1');
return false;
}
elseif ($("input[type=submit]").val() == 'Button 2')
{
alert('you clicked button 2');
return false;
}
});

I need to perform form validation before the form is sent to the server and I need to be able to determine which of the 2 buttons was clicked.

Is it possible to identify which of the 2 buttons caused the form to be submitted using jquery?

回答1:

Does this help!!! http://jsfiddle.net/hun4U/

Instead of formSubmission you can use click events.

HTML:-

<input name="submit" id="submit1" type="submit" value="Button 1">
<input name="submit" id="submit2" type="submit" value="Button 2">

Script

$('#submit1').click(function(){
//do your actions here
});

$('#submit2').click(function(){
    //do your actions here
    });


标签: jquery submit