Possible Duplicate:
jQuery Event Keypress: Which key was pressed?
OK, here's my situation (I've solved this issue in the past, but since I'm not sure my approach was the best, I'm all ears for some advice) :
Submit
button, and the desired action is executed (via Javascript/Ajax, etc)The thing is :
How would you go about this?
The Form
<form id="someId" action="#" method="post"
onsubmit="return false;" onkeypress="return enterSub(this,event);">
...
</form>
The Code
function enterSub(inField, e)
{
var charCode;
if(e && e.which)
{
charCode = e.which;
}
else if (window.event)
{
e = window.event;
charCode = e.keyCode;
}
if (charCode == 13)
{
performThatAction; // My Main action
}
}
To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.
Given an HTML form and the task is to submit the form after clicking the 'Enter' button using jQuery. 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.
$(document). on('keyup keypress', 'form input[type="text"]', function(e) { if(e. keyCode == 13) { e. preventDefault(); return false; } });
The HTMLFormElement. method property represents the HTTP method used to submit the <form> . Unless explicitly specified, the default method is 'get'.
Bind to the submit of the form rather than the click of a button, then prevent the default action.
$("#myform").submit(function(e){
e.preventDefault();
alert("The action has occurred without submitting the form!");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With