-1

The function runs when the user presses enter in the textbox (KeyCode === 13) but i cant get it to work with searchButton

function myFunction(e) {
    if(e.keyCode === 13 || document.getElementById("searchButton").click()){
        e.preventDefault();
        var searchValue = document.getElementById("mySearch").value;
        for(var i = 0; i < users.length; i++){
        if(users[i]['last_name'] === searchValue){
        document.getElementById("return").innerHTML = JSON.stringify(users[i]);
        return;
        }
     }  
  }
}

<input type="search" id="mySearch"  onkeypress="myFunction(event)" />
<button id="searchButton" onclick="myFunction(e)">SEARCH</button>

Is the problem the || expression? The function should run either when the user presses searchButton or presses enter.

2
  • JavaScript .click() always returns undefined Commented Feb 6, 2017 at 22:34
  • check for e.type == 'click' && this.id=='searchButton' Commented Feb 6, 2017 at 22:36

2 Answers 2

7

The call to document.getElementById("searchButton").click() is a programmatic way to simulate a click.

What you probably mean to do is:

function myFunction(e) {
    if((e.target.id === 'mySearch' && e.keyCode === 13) || e.target.id === 'searchButton'){

    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Update This does not work for some reason... I have no idea why as it seems like it should totally work... JsFiddle
There was a missing parenthesis... sorry about that.
0

Ok so when you press the enter key myFunction is called with an event which has the keyCode property, so that is all good.

When you click the button though, the event does not have a keyCode property, and therefore the right side of your conditional document.getElementById("searchButton").click() runs. click is a method that simulates a mouseclick, returning undefined. So the conditional resolves to false, and the rest of the function body will not be run.

You could instead check the type of the event.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.