Restrict input field to two decimals with jQuery

前端 未结 8 785
天命终不由人
天命终不由人 2021-01-12 17:46

I have an input field which I want to restrict so that the user only can input a number with the maximum of two decimals. Want to do this using jQuery.

Could I use j

相关标签:
8条回答
  • 2021-01-12 18:04

    Try this for all symbols:

    inputField.value.replace(/(\...)(.)/, "$1");

    or this for numbers:

    inputField.value.replace(/(\.[0-9][0-9])([0-9])/, "$1");

    I found this method here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Example:_Switching_words_in_a_string

    0 讨论(0)
  • 2021-01-12 18:15

    A similar solution with a backspace hit on reaching more than 2 decimal places.

    function limitDec(id) {
      // find elements
      var amt = $("#testdec")
    
      // handle keyup
      amt.on("keyup", function() {
        if (isNaN(amt.val())) {
          amt.val(0);
        }
        if (amt.val().indexOf(".") > -1 && (amt.val().split('.')[1].length > 2)) {
          amt.val(amt.val().substring(0, amt.val().length - 1));
        }
      })
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <input type="text" id="testdec" onkeyup="limitDec(this.id)" />

    0 讨论(0)
提交回复
热议问题