【问题标题】:I need to allow negative numbers into this function我需要允许负数进入这个函数
【发布时间】:2021-12-07 20:49:36
【问题描述】:

此函数执行以下操作

  • 不允许使用字符
  • 允许退格
  • 有上限
  • 有一个下限
  • 最小步长为 0.1,即没有小于 0.1 的数字,即不是 0.01

什么不工作是允许负数进入函数

<html>
    <input id="setPoint" type="text" name="setPoint" onkeydown="myFunction(event,-80, 150)"   />

<script>


function myFunction(e, low, high) {
  console.log("low" + low);
  console.log("high" + high);

  var nextValue = e.target.value + e.key;
  console.log("NEXT VALUE:" + nextValue);
  if (e.which == 8) { // allow backspace
    return;
  }
  if (!/^(\d+)?([.]?\d{0,1})?$/.test(nextValue)) {
    e.preventDefault(); // non-number, don't allow
  }
  if (nextValue > high) {
    e.preventDefault();
  }
  if(nextValue< low){
    e.preventDefault();
  }
  
}
</script>
</html>

【问题讨论】:

  • @Spectric 你能否修改你的正则表达式以允许负数

标签: javascript html forms input


【解决方案1】:

您的正则表达式几乎完成了,但需要添加一些内容。试试这个正则表达式:

/^-?\d+(\.\d+)?$/

您当前的实现也不允许,例如10.24,上面应该可以正常工作。如果这是故意的,只需将\d+ 更改为\d - 这将确保,如果用户确实输入了.,他们至少有一个数字。

【讨论】:

猜你喜欢
  • 2012-09-25
  • 2015-06-27
  • 1970-01-01
  • 1970-01-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-01-19
  • 2017-06-05
相关资源
最近更新 更多