Allowing Only Numbers And One Decimal
Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it hi
Solution 1:
<inputtype="text"class="decimal" value="" />
And in Js use this
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
Check this fiddle: http://jsfiddle.net/2YW8g/
THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.
Solution 2:
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
functionrun(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
I know it doesn't prevent the wrong char to appear, but it works.
PS: that setTimeout(..., 0)
is a trick to execute the function after the value of the field has already been modified.
Solution 3:
Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5
Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />
$('.decimalPt').keypress(function(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 8 || charCode == 37) {
returntrue;
} elseif (charCode == 46 && $(this).val().indexOf('.') != -1) {
returnfalse;
} elseif (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
returnfalse;
}
returntrue;
});
Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/
Solution 4:
I think it would be best to use something that already exists... like Masked Input Plugin with jQuery
Solution 5:
Try this,
$('input').on('keydown', function (event) {
returnisNumber(event, this);
});
functionisNumber(evt, element) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if ((charCode != 190 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& (charCode != 110 || $(element).val().indexOf('.') != -1) // “.” CHECK DOT, AND ONLY ONE.
&& ((charCode < 48 && charCode != 8)
|| (charCode > 57 && charCode < 96)
|| charCode > 105))
returnfalse;
returntrue;
}
Post a Comment for "Allowing Only Numbers And One Decimal"