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?
The onclick event executes a certain functionality when a button is clicked. This could be when a user submits a form, when you change certain content on the web page, and other things like that. You place the JavaScript function you want to execute inside the opening tag of the button.
JavaScript – Call Function on Button Click Get the reference to the button. For example, using getElementById() method. Call addEventListener() function on the button with the “click” action and function passed as arguments.
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.
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