Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to Prevent Enter From Submitting a Form in Javascript From Certain Input Fields Only [duplicate]

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: 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.

like image 327
Daniel Bingham Avatar asked Jan 10 '10 17:01

Daniel Bingham


1 Answers

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

so in the onkeypress event:

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

and then the JS:

function dontSubmit (event)
{
   if (event.keyCode == 13) {
      return false;
   }
}
like image 169
jedi58 Avatar answered Nov 03 '22 04:11

jedi58