8

This solution was given to this question asking how to trigger an HTML button when Enter is pressed in an input field.

<input type="text" id="txtSearch" onkeypress="searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    if (typeof e == 'undefined' && window.event) { e = window.event; }
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
    }
}
</script>

Why is if (typeof e == 'undefined' && window.event) { e = window.event; } nescecary? It appears to be checking if the argument didn't get passed correctly, why wouldn't it? Is this related to fixing browser compatibility issues?

Community
  • 1
  • 1
Celeritas
  • 14,489
  • 36
  • 113
  • 194
  • 4
    Because of oldIE. But it's not necessary in this case, as you're passing `event` from the inline handler. – bfavaretto May 23 '13 at 19:15
  • Short answer, yes, it's about browser compatibility. – Matt Burland May 23 '13 at 19:15
  • 1
    as a note: one should avoid inline handlers. here is an article explaining some reasons why: http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/ – rlemon May 23 '13 at 19:16

1 Answers1

7

Because old IE versions are a horrible abomination that use a global variable event instead of a function argument like any sane developer would use.

For the same reason (oldIE developers being insane) you cannot use .addEventListener() in oldIE but have to use .attachEvent() instead.

Edit: Just saw that you are using an inline event and always pass the event. That way you will always have a valid event object in the first argument of your function. You do not need the additional code.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • 1
    `onkeypress="some code here"`. See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener for how to do it properly. – ThiefMaster May 24 '13 at 06:46