1

Code:

<input onkeypress="return isNumberKey(event)" type="number" value="" />

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46){   
        return false;
    }   
    return true;
}

The above function allows user to enter value with more than two decimal i.e. 10.5678. How can I modify the function and restrict user to enter values upto two decimal i.e. 10.56

Slimshadddyyy
  • 4,085
  • 5
  • 59
  • 121

1 Answers1

8

Try below code give class number to element

$('.number').on('keypress',function (event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
    var input = $(this).val();
    if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
        event.preventDefault();
    }
});

and for javascript

function isNumberKey(evt){
  
console.log(evt.value);
  if ((evt.which != 46 || evt.value.indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
        //event it's fine

    }
    var input = evt.value;
    if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
        return false;
    }
}
<input onkeypress="return isNumberKey(this)" type="number" value="" />
nirmal
  • 2,143
  • 1
  • 19
  • 29