I see on many sites that the enter key will submit a form but you could also click on the button to submit. Is there a trick to this? Or can a button have two different types of functions attached?
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
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.
Definition and UsageThe formaction attribute specifies where to send the form-data when a form is submitted. This attribute overrides the form's action attribute. The formaction attribute is only used for buttons with type="submit" .
If you have a properly marked up form with an input element of type=submit as your submit button, the enter button should submit the form by default (when focused in an input element of type=text). Clicking works as well.
Any processing code would go on the form's "onsubmit" event instead of the button's "onclick" event. Additionally, you can return false to cancel the form submission (for example, if form validation fails).
My dear there is nothing tricky. Just put the type of the button as submit
and your will achieve what you are wanting. See This
After UPDATE
When there is a form
tag in your html page, enter button always submit the form. If you have made your own button having type="button"
even then you can submit form onclick it.
<input type="button" onclick="submitform();" value="Button">
and here is your javascript function
function submitform()
{
document.forms["myform"].submit();
}
Hence your both cases can be achieved
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