I am trying to trigger the submit button when a user presses enter. Works great for all browsers except Internet Explorer 9. Strange thing is that IE insists on also triggering the click for another button I never told it to. Am I doing something wrong or how to fix this?
Below is my code. Pressing enter in IE triggers the submit click as expected, but for some reason also triggers the "some button" click (even without my keypress listener):
$('input[type=submit]').click(function () {
alert('Submit click');
});
//SIMULATE CLICK IF ENTER PRESSED IN SEARCH
$('input[type=text]').keypress(function (event) {
var keycode = event.keyCode || event.which;
if (keycode == 13) $('input[type=submit]').click();
});
//ROUTE CLEAR HANDLER
$('button').click(function () {
alert('Button click');
});
You can see the bug in action here: http://jsfiddle.net/h64xD/
Here are a couple of things to consider:
IE9 counts the <button/>
element as type="submit"
by default. So to make it non-submit, you have to be explicit:
<button type="button">Some button</button>
If you do that, you will notice that the emulated click
event now doesn't trigger the <button/>
but still fires 2 events. The reason is that, because you haven't explicitly defined a <form/>
element, IE9 assumes the controls as being in a form, and thus pressing enter
in the textbox triggers 2 events:
So again to get around this issue, you have to be explicit:
<button type="button">Some button</button>
<form><input type="text" /></form>
<input type="submit" value="Submit" />
Now, these are the reasons that you are seeing the behaviour in IE. @MrSlayer's answer caters to the second issue of stopping the keypress
event after you have satisfactorily handled it, using preventDefault()
The Enter key has a default behavior to submit, so you need to prevent the default behavior from executing. Because the button
tag is, by default, type="submit"
it is executing that button when the Enter key is pressed.
//SIMULATE CLICK IF ENTER PRESSED IN SEARCH
$('input[type=text]').keypress(function (event) {
var keycode = event.keyCode || event.which;
if (keycode == 13)
{
event.preventDefault();
$('input[type=submit]').click();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With