Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE bug triggers click for 2 buttons?

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/

like image 217
TruMan1 Avatar asked May 24 '12 14:05

TruMan1


2 Answers

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:

  • the one that you are emulating
  • the default form submit button behaviour

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()

like image 122
bPratik Avatar answered Oct 02 '22 14:10

bPratik


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();
    }
});
like image 35
Jeff Jenkins Avatar answered Oct 02 '22 14:10

Jeff Jenkins