简体   繁体   中英

How to disable the enter button from triggering the onkeyup event?

In my asp.net solution, I have a text input box and a search button. There is a onkeyup jquery event on the text input field so it automatically clicks the search button when the user presses a key. You can also manually click the button.

But what I noticed is that if you are typing, and then you press ENTER key, it will trigger the on onkeyup event. How can I disable the function from occurring if the ENTER key was pressed, or maybe detect if it was the ENTER key and then have an if statement or something.

Another thing that is happening is, if there is something wrong with the text in the input box, I display an alert message box. Then if you press ENTER to close the box, it will somehow trigger the onkeyup event, which displays the alert box again...

Thanks.

在函数中所有动作之前添加if (evt.keyCode != 13) :)

You can use .which on the event to determine the KeyCode for the key that was pressed (ENTER = 13):

$('#input').keyup(function(event) {
    if(event.which == 13)
    {
         //respond to enter keypress
    }


});

Also you can use this site to easily find info about keyups/downs etc for different keys.

Hope this helps!

Hope this helps.

<script type="text/javascript"> 

function stopRKey(evt) { 
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
} 

document.onkeypress = stopRKey; 

</script>

The onkeyup event is triggered after an alert when you close it with ENTER because the alert is close onkeydown , and so after it's closed and the document regains focus, when you release the key, the textbox's onkeyup event will be triggered.

As previously stated, you can add an if (event.keyCode != 13) to test if the ENTER key is not the key that was pressed.

A better solution would be to use a different event. Instead of onkeyup , use oninput .

The oninput event is triggered when the user changes the textbox's value.

The event will fire only when the user writes something in the textbox or deletes something. It will not go off when the ENTER key is pressed, or when any other key that doesn't change the textbox's value (like arrow keys) is pressed.

The oninput event might be a better choice for the functionality you're searching for.

*if you're using the oninput event you don't need the if mentioned before.

A fiddle for demonstration of the oninput event: Here

For future reference I found this useful site:

http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM