Sean Flannery
Sean Flannery

Reputation: 1

How to disable enter key in input field

I am trying to stop the enter key from triggering all actions from other scripts on input fields.

Here is the code I am using:

 $(document).bind("keydown", function(e) {

      var code = e.keyCode || e.which; 

          if (code  == 13) {  
          // alert('enter pressed');
          e.preventDefault();
          return false;

      }
 });

An example of the code in action is here http://jsfiddle.net/8SJYn/ , It should be disabling enter but it is not.

Opinions?

Upvotes: 0

Views: 5692

Answers (3)

Joe Daley
Joe Daley

Reputation: 46446

JavaScript events have a "bubbling" phase, where they fire first on the inner-most DOM element, and then work their way up to the top-level document. If you try to stop the event at the document level, as in your example code, it is too late.

In some browsers (Firefox, for one) there is a "capturing" phase that occurs before the bubbling phase, and it works in the opposite direction: from top down. You cannot add a capturing phase event handler using jQuery. You must use the native addEventListener function and pass true as the third parameter. If you add the code below into your jsfiddle, it will prevent the Enter keydown event in some browsers.

document.addEventListener('keydown', function (e) {
    if (e.keyCode === 13) {
        // alert('Enter keydown');
        e.stopPropagation();
    }
}, true);

Be aware that the tag-it control in your jsfiddle also performs its text-to-tag conversions on blur, so if you uncomment the alert statement above, it will perform its text-to-tag conversion anyway, because of the blur event that occurs when the alert message is displayed.

Lastly, if you want to prevent not just other scripts from processing the Enter keydown, but also the browser itself, add an e.preventDefault(); line to the above.

Upvotes: 0

PSL
PSL

Reputation: 123739

You can do it by turning off the keydown and blur events for the input created by the tagit for this element alone.

Try this:

$('#myTags + ul .ui-autocomplete-input').off('keydown').off('blur');

http://jsfiddle.net/JzJRY/

Upvotes: 2

Fibericon
Fibericon

Reputation: 5793

Go into tag-it.js, and on line 245, find this part and remove it:

event.which === $.ui.keyCode.ENTER

Upvotes: 0

Related Questions