开发者

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

This question already has answers here: Prevent users from submitting a form by hitting Enter (36 answers) Closed 6 years ago.

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 k开发者_StackOverflow社区eystroke.

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.


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;
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜