Reputation: 99
I am trying to find a way to limit a text input to a number and quarter decimal increments. For example 0.25, .5,2.75,4.0,10.5 etc. Basically an integer 0-9 and then a decimal 0,.25,.5,.75. I have tried to base it off of
<script>
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
</script>
This limits the input to a decimal number, but can't really figure out how to limit to quarter decimal increments as illustrated above. Any ideas?
Upvotes: 4
Views: 1720
Reputation: 4539
This can be accomplished with the step
attribute of the input html element without the need for any other javascript.
<input step="0.25" type="number"/>
Here is a jsfiddle of it working.
Upvotes: 3
Reputation: 1855
e.KeyCode == 8
to dismiss change on backspacesuse blur event to put correct number if its not correct
function decimalPlaces(num) {
var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
if (!match) { return 0; }
return Math.max(
0,
// Number of digits right of decimal point.
(match[1] ? match[1].length : 0)
// Adjust for scientific notation.
- (match[2] ? +match[2] : 0));
}
jQuery('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g,'');
if(e.keyCode == 8 || decimalPlaces(this.value) < 2){
return true;
}
else if(this.value % 1 != 0)
this.value = (Math.round(this.value * 4) / 4).toFixed(2);
});
jQuery('.numbersOnly').on('blur',function () {
if(this.value % 1 != 0)
this.value = (Math.round(this.value * 4) / 4).toFixed(2);
});
a working fiddle
Upvotes: 5