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 astype="submit"by default. So to make it non-submit, you have to be explicit:If you do that, you will notice that the emulated
clickevent 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 pressingenterin the textbox triggers 2 events:So again to get around this issue, you have to be explicit:
Now, these are the reasons that you are seeing the behaviour in IE. @MrSlayer‘s answer caters to the second issue of stopping the
keypressevent after you have satisfactorily handled it, usingpreventDefault()