The input box prohibits the input of characters other than numbers and decimal points (two ideas and methods)

To realize that the input box prohibits the input of characters other than numbers and decimal points, there are two ideas:

  1. Use the input event and regular to input non-digits and characters other than the decimal point, directly replaced with empty
  2. Use the keydown event and block the default event to directly prohibit the input when inputting characters other than numbers and decimal points

Let's implement the above two methods below, in order to let more students understand and understand, so I did not use the framework here, and directly use the native js (I haven't written it for a long time, it's rusty)

Input events and regular
<body>
    <div>
      <input type="text" oninput="inputNumber(this)">
    </div>
    <script>
      function inputNumber(e) {
     
     
        e.value = e.value.replace(/[^0-9.]/g,"")  // 不可输入数字和小数点以外的
      }
    </script>
</body>
keydown event and blocking default event
<body>
    <div>
      <input type="text" id="input_">
    </div>
    <script>
      let input_ = document.getElementById("input_");
      input_.onkeydown = function(e) {
     
     
        let _code =  e.keyCode 
        if ( (_code < 48 || _code > 57) && _code != 190 && _code != 8){
     
     
          // 输入 除数字 小数点 删除键 以外的均阻止
          e.preventDefault();
        }
      }
    </script>
</body>

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/106374355