Reputation: 9
I need the validation on each key press
<strike><input type="number" value="" id="phno" name="num" onkeydown="return isNumber()" /></strike>
function isNumber(){
var s= document.getElementById("phno").value;
if(isNaN(phno)){
alert("mistmatch");
}
}
How do I validate on each key press (probably the keyup event)
Upvotes: 0
Views: 7363
Reputation: 192
You can try this
<input type="text" id="myTextBox" />
The script
$("#myTextBox").on('keydown', function(e) {
var key = e.keyCode ? e.keyCode : e.charCode;
var value = $(this).val();
if (key > 57 && ((key == 190 && value.indexOf('.') >= 0) || key != 190)) {
e.preventDefault();
}
});
This will allow users to input decimal value or whole numbers.
Upvotes: 1
Reputation:
Try this:
Pure JS
script
var digits = function(box) {
box.value = box.value.replace(/[^0-9]/g, '');
};
html
<input type="text" placeholder="Digits only" onkeyup="digits(this)"/>
JQuery
script
$(function(){
$('.digits').on('input', function(e){
this.value = this.value.replace(/[^0-9]/g, '');
});
});
html
<input type="text" placeholder="Digits only" class="digits"/>
Upvotes: 2
Reputation: 1371
Use this DOM
<input type='text' onkeypress='validate(event)' />
And this script
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
Hope it Helps
Upvotes: 0