Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing enter on any textbox invokes my Save button click event?

Tags:

asp.net

I have a standard asp.net webform with multiple textboxes (Autopostback=False) on it and a Save button.
Pressing ENTER while in any textbox is causing the server side click event of the Save button to be invoked. If I break and look at the call stack, the click event is the only event listed. I do not have a default button set for the form. If I put another button above the save button, then it gets its click event invoked on any press of enter on a textbox.

Any ideas why this is happening, and how to get it to stop?

like image 529
tbone Avatar asked Dec 09 '25 15:12

tbone


2 Answers

This is the default behaviour for most fields except for text areas.

To get around this you can call a javascript function before the form is submitted to check the keypress.

<script type="text/javascript">
  function allowSubmission() {
  return !(window.event && window.event.keyCode == 13); }
</script>

Then the only way to submit the form is to actually hit submit. However as many people have mentioned, the enter key submitting a form is expected behaviour, so you can always alter the function to do basic validation on the fields, allowing the enter key to submit the form if all the required fields have been filled in.

<script type="text/javascript">
  function allowSubmission() {
  return !(window.event && window.event.keyCode == 13) || validateInput(); }
</script>

Edit: You'd call this function on the OnClientClick method of your submit button. Something like:

<asp:Button id="SubmitBtn" runat="server" OnClientClick="return allowSubmission()"/>
like image 175
Brandon Avatar answered Dec 12 '25 03:12

Brandon


This is true for any webform: if you press enter while an input field has focus, the form will be submitted (except textareas). To stop that, you'll need some JavaScript to capture that event and prevent the form being submitted. Be aware though, pressing enter to submit is expected behavior for many users!

like image 25
Matthew Groves Avatar answered Dec 12 '25 03:12

Matthew Groves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!