Reputation: 2859
I have one form with two submit buttons (submit buttons with different IDs). I want to take different actions on :
Can some one guide me, how can I achieve this through jQuery.
Thanks in advance
Upvotes: 1
Views: 2374
Reputation: 11
$(function(){
$("input").keypress(function(e){
if (e.which == 13){
e.preventDefault();
alert("pressed 'Enter' preventDefault()<br>from Form #"+this.form.id);
// do your custom processing here
}
});
});
works fine for me,
Upvotes: 0
Reputation: 6866
You could do the following (See Live Example):
$(document).ready(function(){
$("input[type='text'],input[type='password']").keypress(function(e){
e.preventDefault();
if (e.which == 13){
alert("User pressed 'Enter' in a text input.");
// do your custom processing here
}
});
$("input[type='submit']").click(function(e){
e.preventDefault();
var submitClicked = e.target.id;
alert("The submit button with id '"+submitClicked+"' was clicked!");
//probably a switch statement here to do your custom processing based on which submit button was pressed.
});
});
The code above will trap for enter keypress on any text or password input... will ignore enter key presses on <textarea>
(a desired effect I would think). Pressing enter on any text or password input will NOT trigger the first submit button click.
Just be aware that you'll have to submit your form manually via the code above by using $([your form selector]).submit();
Upvotes: 2
Reputation: 66398
You can use such code:
$(":input").bind("click keypress", function(evt) {
var keyCode = evt.which || evt.keyCode;
if (keyCode == 13) {
alert("ENTER pressed");
}
else {
var sender = evt.target;
if (sender.type == "submit")
alert("Submit button " + sender.id + " clicked");
}
return true;
});
By handling both click
and keypress
events you can catch all the desired scenarios.
Test case: http://jsfiddle.net/PChVY/
Note that pressing ENTER also triggers the first submit button click
event, so to ignore this you can add global flag.
Upvotes: 2