Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this line of code necessary in clicking a button with JavaScript?

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?

like image 696
Celeritas Avatar asked May 23 '13 19:05

Celeritas


People also ask

What is the JavaScript function used to click on button?

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.

How do you make a JavaScript function run when a button is clicked?

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.


1 Answers

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.

like image 80
ThiefMaster Avatar answered Sep 28 '22 11:09

ThiefMaster