Monday, 19 March 2018

jquery - How to get the Enter key within a textbox to trigger a function and not the first/default button



I am trying to get the Enter key to trigger a function when it is pressed when inside a certain textbox, and not trigger the first or default button.



You can see an example of what is happening here: http://jsfiddle.net/cutsomeat/WZ6TM/1/



If you press other keys you will get an alert box with the keycode, yet if you press the Enter key you will not get the alert box with the keycode, but rather the alert box within the button click event.




Obviously the Enter key is trigger the button. Is there a way to avoid this and instead, capture the Enter key in the keyup event, then trigger another function?


Answer



Try this:



$('#myText').on("keypress", function(e) {
if (e.keyCode == 13) {
alert("Enter pressed");
return false; // prevent the button click from happening
}
});



Demo


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...