Calling a function onKeyup event not working while pressing enter

2k Views Asked by At

This is my code

function searchForProductsInPopup(evt) {
     var charCode = (evt.which) ? evt.which : evt.keyCode;
     alert("in");
     if(charCode == 27) {
          closePopup();
     }
     else if(charCode == 13) {
          closePopup();
          return false;
     }
}

HTML code

<input type="text" 
       class="input-medium focused" 
       id="invoiceSearchKeyWord"
       onkeydown="return searchForProductsInPopup(event);"/>

This function will execute on the keyup event of a textbox, for all the other key my code will give an alert saying in. But when pressing Enter key I'm not getting any alerts and directly the form is submitted, why is that? My knowledge in JS is very limited. Can anybody explain?

1

There are 1 best solutions below

3
On BEST ANSWER

The submit event is triggered before your keyup event:

<form onsubmit="alert('submitted')">
    <input onkeyup="alert('keyup')"/>
</form>

1. submitted
2. Page navigates

https://jsfiddle.net/DerekL/pvw1dtb7/

You will see the expected keyup event if you properly prevent your submit event. Something like this:

<form onsubmit="alert('submitted'); event.preventDefault();">
    <input onkeyup="alert('keyup')"/>
</form>

1. submitted, event stopped
2. keyup

https://jsfiddle.net/DerekL/dmpxjt27/