Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery allow only two numbers after decimal point

I found the following JQuery function here which prevents a user from entering anything that's not a number or a single decimal. The function works well but I'd like to improve it to prevent the user from entering 3 or more decimal places i.e. disallow 99.999 and allow 99.99. Any ideas?

 function checkForInvalidCharacters(event, inputBox){                                  if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {                           event.preventDefault();                        }         }; 
like image 445
user676567 Avatar asked Feb 15 '14 11:02

user676567


People also ask

How do I get 2 decimal places in jQuery?

$("#diskamountUnit"). val('$' + $("#disk"). slider("value") * 1.60);

How do you prevent keypress 2 digits after a decimal number?

keyCode) var newValue = this. value + character; if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) { e. preventDefault(); return false; } });

How do you only allow two numbers after a decimal in a text box?

Use JavaScript for validation input or use step=". 01" , which allows up to two decimal places on keypress input.

How do you round to 2 decimal places in JavaScript?

Use the toFixed() method to round a number to 2 decimal places, e.g. const result = num. toFixed(2) . The toFixed method will round and format the number to 2 decimal places.


2 Answers

The logic is every time a user entering a number you have to check two things.

  1. Has the user entered decimal point?
  2. Are the decimal places more than two?

For the first one you can use $(this).val().indexOf('.') != -1

For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2

EDIT-1
Also, you have to add event.which != 0 && event.which != 8 so that arrow keys and backspace work in Firefox (Manoj comment)

EDIT-2
Also, you have to add $(this)[0].selectionStart >= text.length - 2 so that you can add digits if the cursor is to the left of the decimal point (BIdesi comment)

EDIT-3
Also, you have to check if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. So you have to add $this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); for cutting extra digits (Gilberto Sánchez comment)

EDIT-4
To handle pasted data, you must bind a paste event handler.Then you have to check if pasted data have . withtext.indexOf('.') > -1 and more than 2 digits after the decimal with text.substring(text.indexOf('.')).length > 3. If so, you have to cut extra digits. Also you have to check that user entered numeric input with $.isNumeric() (darasd comment).

Here is the code:

$('.number').keypress(function(event) {      var $this = $(this);      if ((event.which != 46 || $this.val().indexOf('.') != -1) &&         ((event.which < 48 || event.which > 57) &&         (event.which != 0 && event.which != 8))) {             event.preventDefault();      }        var text = $(this).val();      if ((event.which == 46) && (text.indexOf('.') == -1)) {          setTimeout(function() {              if ($this.val().substring($this.val().indexOf('.')).length > 3) {                  $this.val($this.val().substring(0, $this.val().indexOf('.') + 3));              }          }, 1);      }        if ((text.indexOf('.') != -1) &&          (text.substring(text.indexOf('.')).length > 2) &&          (event.which != 0 && event.which != 8) &&          ($(this)[0].selectionStart >= text.length - 2)) {              event.preventDefault();      }        });    $('.number').bind("paste", function(e) {  var text = e.originalEvent.clipboardData.getData('Text');  if ($.isNumeric(text)) {      if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {          e.preventDefault();          $(this).val(text.substring(0, text.indexOf('.') + 3));     }  }  else {          e.preventDefault();       }  });
.number {    padding: 5px 10px;    font-size: 16px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <input type="text" class="number" />
like image 167
laaposto Avatar answered Sep 20 '22 11:09

laaposto


It can also be done with a regular expression:

    $('.class').on('input', function () {         this.value = this.value.match(/^\d+\.?\d{0,2}/);     }); 

Name the css selector .class to whatever you like and put it on the input.

like image 36
Tegge Avatar answered Sep 20 '22 11:09

Tegge