Use js to control the input box to enter only numbers or decimals and allow up to two decimal places. Specific codes

Use js to control the input box to enter only numbers or decimals and allow up to two decimal places. Specific codes

Specific code

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>只允许输入两位小数</title>
</head>
<body>
<input type="text" name="je" onblur="clearNoNum(this)"/><script type="text/javascript">
  function clearNoNum(obj) {
     
     
    obj.value = obj.value.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    obj.value = obj.value.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    obj.value = obj.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    obj.value = obj.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//只能输入两个小数
    if (obj.value.indexOf(".") < 0 && obj.value != "") {
     
     //以上已经过滤,此处控制的是如果没有小数点,首位不能为类似于 01、02的金额
      obj.value = parseFloat(obj.value);
    }
    if (!obj.value || obj.value == '0' || obj.value == '0.0' || obj.value == '0.00') {
     
     
      alert('退款金额不能为空');
      return;
    }
    //  正常得话继续调后端接口
  }
</script>
</body>
</html>

How does js restrict the input input box to only enter numbers

<input type="text"
    class="form-control match-rotation-input"
    maxlength="3"
    οnkeyup="value=value.replace(/[^\d]/g,'')"//输入时校验    
    οnblur="value=value.replace(/[^\d]/g,'')"//失去焦点时校验
    ng-model="schedule.round"
    placeholder="请输入数字">

Added a line

οnkeyup="value=value.replace(/[^\d]/g,'')"

It's relatively simple to use regular expressions here, and then add a hint: placeholder="Please enter a number".

But why add

οnblur="value=value.replace(/[^\d]/g,'')"

What about this line?

This is because in the process of operation, you will find that if you keep pressing the letter keys and then click the mouse to make the input lose focus,

Will cause letters to appear in the input box, so in order to avoid this problem, I added

οnblur="value=value.replace(/[^\d]/g,'')"

Note: I thought about changing the type to: number type, but the style that came out did not meet what we wanted, so we used regular to match

Guess you like

Origin blog.csdn.net/guo_qiangqiang/article/details/111992004