Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent a webform from submiting on 'Enter'

I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:

<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/>
<div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/>
<script type="text/javascript">
  //<![CDATA[
  var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {})
  //]]>
</script>
like image 702
Kyle Boon Avatar asked Nov 18 '25 22:11

Kyle Boon


1 Answers

You should add an event handler to the form itself which calls a function to decide what to do.

<form onsubmit="return someFunction();">

And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.

Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.

like image 106
Zack The Human Avatar answered Nov 21 '25 13:11

Zack The Human