Tim M
Tim M

Reputation: 99

Limit text input to quarter decimal increments

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

Answers (2)

Ryan Gates
Ryan Gates

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

hsh
hsh

Reputation: 1855

  1. use number of decimal places to let user write a number with maximum 2 decimal places
  2. use e.KeyCode == 8 to dismiss change on backspaces
  3. use 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

Related Questions