Roberto Marras
Roberto Marras

Reputation: 153

How to disable enter on input only in some parts?

I am currently running this as I don't want users to press enter on their keyboard to launch an input and it works.

jQuery(window).keydown(function(event){
  if(event.keyCode == 13) {
    event.preventDefault();
    return false;
  }
});

However I have one part of the site where this shouldn't be avoided and i tried the following but it didn't work

if(jQuery(".tab-pane").is("#step6")) {
  jQuery(window).keydown(function(e){
    if(e.keyCode == 13) {
      return true;
    }
  });
}

I guess the first overrides the second

Upvotes: 1

Views: 69

Answers (4)

Jones Joseph
Jones Joseph

Reputation: 4938

Try using classes to make it easy.. just add the class prevent-enter on the inputs you want to avoid the keypress.

$(document).ready(function() {

  $('.prevent-enter').keydown(function(e) {
    if (e.keyCode == 13) {
      e.preventDefault();
      return false;
    }
  });

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="get" action="javascript:alert('form submitted');">
  <input class="prevent-enter" placeholder="This prevents enter keypress" /><br>
  <input class="" placeholder="This accepts enter keypress" /><br>
  <input type="submit" />
</form>

Upvotes: 1

brk
brk

Reputation: 50291

You may need to slightly tweek the code & check this condition inside keydown

jQuery(window).keydown(function(event) {
  // checking current keycode
  if (13 == event.keyCode) {
    // the is condition
    if (jQuery(".tab-pane").is("#step6")) {
      return !0; // will return true
    }
    event.preventDefault(); // otherwise will prevent default behaviour 
    return !1 // will return false
  }
});

Upvotes: 1

prasanth
prasanth

Reputation: 22500

Yes..first function is replace the second one.so use like this .Include the second function inside the first .Events are same, condition only different

jQuery(window).keydown(function(event){
  if(event.keyCode == 13) {
  if(jQuery(".tab-pane").is("#step6")) {
    return true;
}
else{
    event.preventDefault();
    return false;
    }
  }
});

Upvotes: 1

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

I suggest attaching the event of the click to each input not to the window :

<input type="text" onkeypress="myFunction(event)">

myFunction() should be like this :

    function myFunction(e) {
    if (e.keyCode == 13) {
        //do whatever you want
       }
   }

Hope this was useful

Upvotes: 0

Related Questions