Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML onKeyDown-Event calling function and button-click

I'm trying to create a search option.

If someone is using my search field, they can press the "Search-Button" or just press the enter key to start the function.

My problem is that if they press the enter key within the text box it starts my function and after the function it calls the button click.

I've used Google but couldn't solve it, even tried to disable the button while myFunc() is called.

<!DOCTYPE html>
<html>
    <body>
        <form>Search
            <br>
            <input type="text" id="searchField" onKeyDown="if(event.keyCode==13) myFunc()">
            <br>
            <button type="button" id="myButton" onClick="myFunc()">Search</button>
        </form>
    </body>
</html>
like image 729
Arman21 Avatar asked Sep 16 '25 20:09

Arman21


1 Answers

Looks like you want to stop the event propagation in this case. I've changed your code to the following:

<!DOCTYPE html>
<html>
<body>

<form>
  Search<br>
  <input type="text" id="searchField" onKeyDown="if(event.keyCode==13){console.log('Hello World from Input'); return false;}">
  <br>
  <button type="button" id="myButton" onClick="console.log('Hello World from Button')">Search</button>
</form>
</body>
</html>

Pressing enter while the input element has the focus gives me only Hello World from Input at the console.

like image 50
Stefan Braun Avatar answered Sep 18 '25 11:09

Stefan Braun