Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 728
MarkieB Avatar asked Jun 12 '12 17:06

MarkieB


People also ask

How do you submit a form when Enter key is pressed?

To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value. Explanation: We use the jQuery event. which to check the keycode on the keypress.

How do I press Enter key programmatically in HTML?

You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.

How do you check if the enter key is pressed?

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox'). keypress(function(event){ var keycode = (event.


1 Answers

Try this:

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

Demo

like image 104
sachleen Avatar answered Sep 19 '22 11:09

sachleen