Reputation: 15043
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?
Upvotes: 8
Views: 149
Reputation: 318518
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.
Upvotes: 7