1

Hi I tried to use this code to limit user's input. A problem is I cannot use my return key or the enter in my keyboard in the input box. How can I solve my problem. Im using this code:

$("input").keypress( function(e) {
    var chr = String.fromCharCode(e.which);
    if ("bcdegkmnqupvxy36789".indexOf(chr) < 0)
        return false;
});
  • Can you please clarify the problem? You want to use the enter key specifically for this? `function (e) { if (e.which === 13) stuff(); }` might help. – Sam Creamer Aug 21 '17 at 13:06
  • Have a look at this https://stackoverflow.com/questions/8669268/limit-number-of-characters-in-input-field – mahi Aug 21 '17 at 13:08
  • What about mouse input,..eg. right click paste?. – Keith Aug 21 '17 at 13:20

4 Answers4

2

To achieve what you need you can simply add another condition to the if statement which checks for the Return keycode: 13:

$("input").keypress(function(e) {
  var chr = String.fromCharCode(e.which);
  if ("bcdegkmnqupvxy36789".indexOf(chr) < 0 && e.which != 13)
    return false;
   
  console.log('allowed');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="foo" />
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    You didn't mention tab in the question, but that's keycode `9`. You need to add that (and any other keys you want to enable) to the `if` statement as well – Rory McCrossan Aug 21 '17 at 13:13
  • I was making a point that manually entering all the allowed keys (like tab, shift, backspace) is a bad way of doing it. You only want to potentially prevent the default from occurring when the user strikes a key that has a character attached to it. – Adam Jenkins Aug 21 '17 at 13:15
0

Just update your if condition to allow e.which === 13 (which is the Enter key) as follows:

$("input").keypress( function(e) {
    var chr = String.fromCharCode(e.which);
    if ("bcdegkmnqupvxy36789".indexOf(chr) < 0 && e.which !== 13) {
        return false;
    }

    console.log( e.which, chr, 'allowed' );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />
lumio
  • 7,428
  • 4
  • 40
  • 56
0

You only want to limit the input if the user has entered a character and not hit one of the non-character entering keys (like tab, of return/enter).

So check to see if chr is not false-y (e.g. an empty string) first:

$("input").keypress( function(e) {
    var chr = String.fromCharCode(e.which);
    //if chr is a non-character keycode (like 13) then you won't return false
    if (chr && "bcdegkmnqupvxy36789".indexOf(chr) < 0)
        return false;
});
Adam Jenkins
  • 51,445
  • 11
  • 72
  • 100
0
$("input").keypress( function(e) {
var chr = String.fromCharCode(e.which);
if ("bcdegkmnqupvxy36789".indexOf(chr) < 0 && e.which !=13 && e.which !=8) 
    return false;
});
DevFast
  • 7
  • 3