Getting How a Form Was Submitted on submit event
I have a form that has a couple of buttons on it. Two of the buttons use ajax to submit the form and clear it 开发者_如何学Cso that the user can add multiple records before moving on. The last button is for when the user is done with the page and wants to move onto the next page. Is it possible in jQuery's .submit() method to tell how the form was submitted (hitting enter, or get the object of the button clicked)?
Not sure if it is best practices, but I found that if I create a submit event handler and then after that create the handlers for the other buttons it seems to work okay, at least in Chrome.
Here's an example
$(function(){
$('form#frmField').submit(function(evt){
alert('Form Submitted');
return false;
});
$('input#btnReset').click(function(){
alert('Form Reset');
return false;
});
});
You can define onclick event handlers for your buttons which would save the state into some global-scope variable. Then you would check the state of the variable at onsubmit handler.
http://jsfiddle.net/archatas/6dsFc/
you can try this way:
HTML:
<form id="myform">
<input type="text" id="text1" name="text1" /><br />
<input type="button" class="button-submit" id="b1" name="b1" value="send 1" /><br />
<input type="button" class="button-submit" id="b2" name="b2" value="send 2" /><br />
<button class="button-submit" id="b3">send 3</button>
</form>
<br />
<div id="data"></div>
JS:
$('#myform').bind('submit', function(event, from) {
if(from)
$('#data').append("from :" + $(from).attr('id') + '<br />');
return false;
});
$('#myform').keypress(function(event) {
if (event.which == '13') {
event.preventDefault(); //preventDefault doesn't stop further propagation of the event through the DOM. event.stopPropagation should be used for that.
event.stopPropagation();
$(this).trigger('submit', [this]);
return false;
}
});
$('.button-submit').bind('click', function(event) {
event.stopPropagation();
$('#myform').trigger('submit', [this]);
return false;
});
example
event.preventDefault
jQuery events pass an event object through their calls. You can use this event object to determine how the event was called.
Specifically, if you pass it as a parameter e
in the function, you can check e.type
, which should be equal to click
, or e.which
, which if it was submitted with an enter, would be 13.
You can use target
to find out which DOM element initiated the submission with e.target
.
So,
jQuery('#foo').click(function(e){
var initiator = $(e.target); //jQuery object for the DOM element that initiated the submit
if(e.type==="click")
{
//is a click
}
else if(e.which==="13")
{
//is an 'enter' triggered submission
}
});
});
精彩评论