Validation for number with jquery
How can write jquery code that input just accept number. if was something except number typed does not allow(mean if user type word typed stop, field just accept number no word). How is it without use plugin?
<input type="text" name="passport_number" class="number">
开发者_如何学Go
quick and dirty:
$('input').bind('keyup change',function(){
var v = parseInt($(this).val());
$(this).val(isNaN(v)?'':v);
});
demo:
http://jsfiddle.net/Q9zrw/1/
different approach:
$('input').bind('keyup change',function(){
$(this).val($(this).val().replace(/\D/g,''));
});
The function below allows numbers and the delete and backspace keys.
function numbersOnly() {
var key_code = window.event.keyCode;
var oElement = window.event.srcElement;
if (!window.event.shiftKey && !window.event.ctrlKey && !window.event.altKey) {
if ((key_code > 47 && key_code < 58) || (key_code > 95 && key_code < 106)) {
if (key_code > 95) {
oElement.value = oElement.value;
}
}
else if (key_code == 8) {
oElement.value = oElement.value;
}
else if (key_code == 37 || key_code == 39 || key_code == 46) {
}
else if (key_code != 9) {
event.returnValue = false;
}
} else {
event.returnValue = false;
}
}
I actually wrote something just like this recently:
var oldnumber=0;
var $ctrl=$('input[name=passport_number]');
$ctrl.focusout(function () {
if (isFinite($ctrl.attr('value'))) {
oldnumber=$ctrl.val();
} else {
$ctrl.attr('value',oldnumber);
}
});
Basically, if you type in a number, it remembers that number. If you write anything but a number, the field is set back to its previous value.
My solution is decently short and pretty darn clean if you ask me. It checks if it is a number, if not, it denies your entry.
Hope that helps :)
For fixed-width data like passport numbers, use the masked-input plugin. For general numeric input, use the numeric plugin. I have used both and they work very well. For generic tasks like these, it is likely that someone has already created a plugin.
BTW, keystroke-level UI programming like this is trickier than it might initially appear. You need to handle the character keys, left and right arrow, backspace and delete, and not break tab, enter, and Control-A. Ideally you should also handle the case where the user has selected a range of text for deletion or replacement.
I think this is a better approach because it don't escape any content to the input.
$('input').bind('keypress',function(){ if(isNaN(String.fromCharCode(window.event.keyCode))) window.event.returnValue = false; });
Hope it help :)
Try:
var passport_field = $(....)
if (passport_field.val() != parseInt(passport_field.val()))
return false;
精彩评论