JQuery allow only two numbers after decimal point

前端 未结 7 927
春和景丽
春和景丽 2020-12-02 10:31

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 i

7条回答
  •  情话喂你
    2020-12-02 11:27

    I've updated the function for a few extra cases.

    1. It will allow negative numbers
    2. It will allow you to edit the left of the decimal when there are already 2 digits to the right
    3. It allows you to use the arrow keys and backspace when you are in Firefox
    4. It also handles pasted data

    /**
     * Given an input field, this function will only allow numbers with up to two decimal places to be input.
     * @param {object} element
     * @return {number}
     */
    function forceNumber(element) {
      element
        .data("oldValue", '')
        .bind("paste", function(e) {
          var validNumber = /^[-]?\d+(\.\d{1,2})?$/;
          element.data('oldValue', element.val())
          setTimeout(function() {
            if (!validNumber.test(element.val()))
              element.val(element.data('oldValue'));
          }, 0);
        });
      element
        .keypress(function(event) {
          var text = $(this).val();
          if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point
            ((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number
              (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
              (event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF)
            event.preventDefault(); //cancel the keypress
          }
    
          if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
            ((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected
            (element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
            (event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
            (event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF)
            event.preventDefault(); //cancel the keypress
          }
        });
    }
    
    forceNumber($("#myInput"));
    
    

提交回复
热议问题