Kenth Joshua Espina
Kenth Joshua Espina

Reputation: 87

jQuery allow selected characters only keypress function

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

Upvotes: 1

Views: 1222

Answers (4)

DevFast
DevFast

Reputation: 7

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

Upvotes: 0

Adam Jenkins
Adam Jenkins

Reputation: 55623

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

Upvotes: 0

lumio
lumio

Reputation: 7575

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 />

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

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" />

Upvotes: 2

Related Questions