正则表达式仅匹配数字和单位,退格键出现问题

4
如何创建一个只接受数字并始终在结尾添加单位的输入字段?
使用正则表达式仅接受数字的解决方案如下:
HTML:
    <input name="distance">

JavaScript(带有jQuery):
     $('input[name="distance"]').on('input', function() {
        this.value = this.value.replace(/[^0-9]/g, '').replace(/^([\d]+)$/g, '$1 km');
    });

工作正常,但当我尝试使用退格键来更正信息时出现了一些问题。

2
你在尝试将\d用作一个反斜线和字符d的文字表示,还是用作数字简写符号?如果你是用它作为简写符号,那么[\d]就没有意义,因为\d === [0-9] - Taplar
2个回答

3

将光标设置在数字值的末尾,本例中数字值为输入值的倒数第-3位,因为字符串“ km”。

还要检查光标是否超过数字值(如果光标位于附加字符串“ km”中),如果超过,则将光标移动到数字值的末尾。

$('input[name="distance"]').on('input', function() {
  this.value = this.value.replace(/[^0-9]/g, '').replace(/^([\d]+)$/g, '$1 km');

  var fieldInput = $(this);
  var fldLength = fieldInput.val().length;
  fieldInput.focus();

  var pos = fieldInput[0].selectionStart;
  // if cursor position is past the number value, reset the cursor to the end of the number value.
  if (pos > fldLength - 3) {
    fieldInput[0].setSelectionRange(fldLength - 3, fldLength - 3);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="distance">


哦,看起来是个很棒的解决方案!谢谢。 - Evandson Dantas
1
@EvandsonDantas 我编辑了我的答案,包括检查光标位置,如果它超过数字值,那么我们将重新定位它。这使用户可以在需要时在值的中间进行编辑。 - Souleste

3

不需编辑输入的替代方案

可能更简单和更简洁的方式是在输入框右侧(或者 内部)显示单位,就像我在下面的代码片段中展示的那样。

这种方法更简单,通常更易于用户理解(在 UI 方面更好)。

我还将正则表达式从[^0-9]更改为\D(因为它们相同,只是\D更短)。

$('input[name="distance"]').on('input', function() {
    this.value = this.value.replace(/\D/g, '');
});
*,input {
  font-family: Arial !important;
  font-size: 16px;
}
input {
  padding-right:1.5em;
  text-align:right;
}
input ~ span.unit {
  margin-left:-1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name='distance'/><span class=unit>km</span>


输入类型为数字

除了上述逻辑,您还可以使用<input type=number />,并像以下代码片段建议的那样放弃jQuery。

所有当前的浏览器都支持这个输入类型:Mozilla 输入数字文档.

*,input {
  font-family: Arial !important;
  font-size: 16px;
}
input {
  padding-right:1.5em;
  text-align:right;
}
input ~ span.unit {
  margin-left:-1.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=number /><span class=unit>km</span>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接