Formatting input

Asked

Viewed 40 times

1

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

  • Accept only number and points;
  • Accept only one point;
  • After the point only accept 8 decimal places;

the part of accepting only number and only one point I managed perfectly, but I’m breaking my head with the decimal places.

fiddle: https://jsfiddle.net/mhk8a4yo/

1 answer

0


You can try something like adding another validation. It’s 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();
});
  • 1

    It works though, there is a problem in firefox browser where the Backspace key stops working, probably something related to Event.which.. but thank you!

  • Hello, for nothing. If you used the code, please select the answer as the correct answer to your question. Thank you.

Browser other questions tagged

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