In HTML, a form can be submitted by
- clicking the submit button
- pressing enter when the focus is on the submit button
- by pressing enter on the input field
Is there a way to find out which of the three methods was used to submit the form?
In HTML, a form can be submitted by
Is there a way to find out which of the three methods was used to submit the form?
HTML doesn't have any built-in way of knowing, as far as I know. You'd have to catch the necessary events and keep the state in memory. Something like the following:
bool
to true when the input receives focus. Set it back to false when it loses focus.bool
to true when the button receives focus. Set it back to false when it loses focus.bool
to truebool
to true.Now you should have the necessary information to know what actions the user took to submit the form. jQuery should be able to help you with all these events.
Also, I believe the form is also submitted when the form has focus (so not just the button or the input) and you press enter. I'm not sure if this is the actual form having focus, or any control inside the form.
So, what you're trying to achieve will require some hacking around. Are you sure you can't provide your users the experience you want in some other way?
I would use the keypress
method of jquery to capture if a user is pressing the enter key. Along with the mousedown
method to capture the click. The jquery and HTML code would look like this:
HTML:
<form id="myForm">
Name<input type="text" />
Address<input type="text" />
<button id="submitBtn" type="button">Submit</button>
</form>
jQuery Code:
$('#submitBtn').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key on the submit button');
}
event.stopPropagation();
});
$('#myForm').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
alert('You pressed "enter" key in the input field');
}
event.stopPropagation();
});
$('#submitBtn').mousedown(function(event){
alert('You clicked submit');
event.stopPropagation();
});
Just apply different function to each action. To prevent the form fires its default action, you have to put return false;
or event.preventDeafult();
in the callback function.
see the example: http://jsfiddle.net/6krYM/
HTML:
<form>
<input type='text' id='input'>
<input type='submit' value='submit' id='submit-button'>
</form>
JavaScript:
$("#submit-button").click(function(){
alert("click on submit button");
return false;
});
$("#input").keypress(function(e){
if (e.which == 13){
e.preventDefault();
alert("press enter in text");
}
});
$("#submit-button").keypress(function(e){
if (e.which == 13){
alert("press enter on button");
}
return false;
});