views:

275

answers:

4

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>
+2  A: 

Trap the event and cancel it.

It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.

le dorfier
+1  A: 

You could use a regular button that submits the form on click instead of your submit button.

If you want the enter key to work in other fields, just handle it there and submit the form.

Alex Brault
+1  A: 

in the input element for the button do:

<input type='submit' value='submit' onclick='submiFunction(); return false;'>

or on the form itself

<form blabla onsubmit='someAjaxCall(); return false;'>

Which should stop the form from submitting.
the return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)

Pim Jager
I think the event will still bubble up to the default, unless you explicitly cancel it.
le dorfier
the "return false;" should be the explicit cancel call.
Pim Jager
+6  A: 

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.

Zack Mulgrew