Limit number of decimal place characters javascript

4

The user can enter values into an input text. What happens, I want to limit the number of characters after the period. Valid example:

  

2.324

     

2343423.432

That is, the user can not enter more than three decimal places. Each time a character is entered, I have to validate this situation. When this happens, the input will not let you enter another decimal place.

    
asked by anonymous 20.08.2015 / 11:37

1 answer

4

I think you can use something like this:

var input = document.querySelector('input');
var oldVal = '';
input.addEventListener('keyup', function(){
    var parts = this.value.split('.');
    if (parts && parts[1] && parts[1].length > 3) this.value = oldVal;
    oldVal = this.value;
});

The idea is to split the string with . and know the length ( length ) of the part after the point. If it is greater than 3, then replace the value with the old one.

jsFiddle: link

    
20.08.2015 / 11:53