Formatting input

1

Hello, I'm having a big problem with javascript. I need an input field that is formatted as follows:

  • Only accept number and periods;
  • Accept only one point;
  • After the dot only accept 8 decimal places;

The part of accepting only number and only one point I got perfectly, but I'm breaking the head with the decimal places.

follows fiddle: link

    
asked by anonymous 01.05.2018 / 19:57

1 answer

0

You can try something like adding more validation. Not the best answer, but I think it will solve:

$('#campo').keypress(function(event) {
    if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
            $(this).val().indexOf('.') != -1) && 
            (event.which < 48 || event.which > 57) ||
            $(this).val().indexOf('.') != -1 && 
            $(this).val().split('.')[1].length >= 8) {
        event.preventDefault();
    }
}).on('paste', function(event) {
    event.preventDefault();
});
    
01.05.2018 / 20:24