Reputation: 17520
How to code in jQuery so a user can not press dot "." key in a text box ?
i can code it in javascript like that, on each keypress the browser checks if a key is pressed, if it is dot then substring(0,len-1), but it flickers ! i want to completely block pressing the key !
Upvotes: 3
Views: 9211
Reputation: 342655
This should work. It has not been cross-browser tested:
$("#theTextBox").keyup(function() {
if($(this).val().indexOf('.') !== -1) {
var newVal = $(this).val().replace('.', '');
$(this).val(newVal);
}
});
EDIT: I think this is better:
function doItPlease() {
if ($(this).val().indexOf('.') !== -1) {
var newVal = $(this).val().replace('.', '');
$(this).val(newVal);
}
}
$("#theTextBox").bind("keydown keyup", doItPlease);
Try the less sucky solution here.
EDIT (again): I favour the above solution, because I quite like the feedback aspect. That said, I think this is what you're after:
$("#theTextBox").keyup(function(e) {
if (e.which != 190) {
return true;
}
e.preventDefault();
});
Upvotes: 5
Reputation: 42818
Use the excellent http://bassistance.de/jquery-plugins/jquery-plugin-validation/ form validation plugin.
All you need to do to validate is issue the options as a class name:
HTML
<input id="test" type="text" class="required email"/>
Adding required
and email
as a class will validate it as a required input that must be an email. Validation is done as you type.
jQuery
$('#test').validate()
The great thing about this plug-in is you can access the js file directly from Microsoft CDN so you don't' have to load it from your server. http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.js
Upvotes: 1
Reputation: 24515
Have a look at this plugin to prevent specific characters being entered: http://www.itgroup.com.ph/alphanumeric/
Also have a look at the validation plugin for general validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
Upvotes: 3