How do I prevent user from entering specific characters in a textbox using jQuery?
Try using the fromCharCode method:
$(document).ready(function () {
$('#tb1').keydown(function (e) {
var k = String.fromCharCode(e.which);
if (k.match(/[^a-zA-Z0-9]/g))
e.preventDefault();
});
});
You use keypress
rather than keydown
and prevent the default action.
For example, this prevents typing a w
into the text input:
$("#target").keypress(function(e) {
if (e.which === 119) { // 'w'
e.preventDefault();
}
});
Live Copy | Source
Update: If it's applying the regex that's giving you trouble:
$("#target").keypress(function(e) {
if (String.fromCharCode(e.which).match(/[^A-Za-z0-9 ]/)) {
e.preventDefault();
}
});
Live Copy | Source