views:

112

answers:

1

I have a form for which onkeyup triggers the creation of a suggestions box for certain fields. I am able to capture the keystrokes for the up arrow, for the down arrow and for escape and use them accordingly to move around in the suggestions box or close it. I would like to use enter to move their selection into the input field that triggered the suggestions. However, I seem to be unable to capture the enter keystroke.

Control never enters my javascript suggest function. Rather the form simply submits. I've tried noEnter functions that return false on enter passed into onkeypress and onkeydown for the input element in question, no dice. The form seems to grab control from all of the input event handlers and submit itself before any of them can do anything.

Does form submit override all other event handlers in fields, or is there something else going on here? If it does, is there some way around that?

Here's the element in question (some values removed):

<input type="text" name="myInput" id="myInputField" size="22" onkeypress="noEnter(event)" onkeyup="suggest(event)" onblur="hideSuggestions()">

And here's the javascript to catch it:

    var evnt = (event ? event : window.event);

    var key = evnt.keyCode;

    if(key == 13) { // Handle Enter
        alert("ENTER PRESSED.");
        hideSuggestions();
        return false;
    }

The alert never fires. Alerts put at the top of the function never fire either. For the escape key however, when I place the exact same code in an if checking for key == 27 the alert fires.

There are other questions on almost the same topic, such as this one: http://stackoverflow.com/questions/923683/prevent-users-from-submitting-form-by-hitting-enter-2

However, I am not using jquery and I only want to prevent enter from submitting for this one field. But none of the other solutions mentioned in various questions seem to work.

EDITTED: To explain where key is set.

+4  A: 

try changing the onkeyup event on the input to return the function result

so:

<input type="text" name="myInput" id="myInputField" size="22" onkeyup="return dontSubmit(event);" />

and then the JS:

function dontSubmit (event)
{
   if (event.keyCode == 13) {
      return false;
   }
}
jedi58
NICE! That did it, thank you!
Daniel Bingham