Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  89] [ 6]  / answers: 1 / hits: 17811  / 9 Years ago, thu, september 10, 2015, 12:00:00

My requirement is to not allow user to type in any Alphabets. The below code allows 1 character to be entered even though I have provided the e.preventDefault() method on both keydown and keyup methods.





$(function() {
// Regular Expression to Check for Alphabets.
var regExp = new RegExp('[a-zA-Z]');

$('#test').on('keydown keyup', function(e) {

var value = $(this).val();

// Do not allow alphabets to be entered.
if (regExp.test(value)) {
e.preventDefault();
return false;
}

}); // End of 'keydown keyup' method.

}); // End of 'document ready'

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>

<input type=text id=test name=test />





What am I doing wrong? Is there some other way to get this done?


More From » jquery

 Answers
5

Replace



var value = $(this).val();


by



var value = String.fromCharCode(e.which) || e.key;


After all, you need to check which key has been pressed before allowing a character to be typed into the field.



Also, make sure the backspace and delete buttons and arrow keys aren’t blocked!





$(function() {
var regExp = /[a-z]/i;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;

// No letters
if (regExp.test(value)) {
e.preventDefault();
return false;
}
});
});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>

<input type=text id=test name=test />





If your goal is to only accept numbers, dots and commas use this function instead:





$(function() {
var regExp = /[0-9.,]/;
$('#test').on('keydown keyup', function(e) {
var value = String.fromCharCode(e.which) || e.key;
console.log(e);
// Only numbers, dots and commas
if (!regExp.test(value)
&& e.which != 188 // ,
&& e.which != 190 // .
&& e.which != 8 // backspace
&& e.which != 46 // delete
&& (e.which < 37 // arrow keys
|| e.which > 40)) {
e.preventDefault();
return false;
}
});
});

<script src=https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js></script>

<input type=text id=test name=test />




[#65117] Tuesday, September 8, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sashacitlallik

Total Points: 30
Total Questions: 100
Total Answers: 85

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;