Limit the number of characters of javascript decimals

Asked

Viewed 1,705 times

4

You can enter values into an input text. What happens is that I want to limit the number of characters after the point. Valid example:

2.324

2343423.432

That is, the user cannot enter more than three decimal places. Each time a character is inserted, I have to validate this situation. When this situation happens, the input will not let you write any more decimal places.

1 answer

4


I think you can wear something like that:

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 break the string by . and know the length (length) of the part after the point. If it is greater than 3, then replace the value with the old.

jsFiddle: http://jsfiddle.net/r9knc3zg/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.