我如何创建一个仅接受数字并始终在末尾添加单位的输入字段?
使用正则表达式只接受数字的解决方案是:
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');
});
工作正常,但是当我尝试使用退格键更正信息时出现了一些问题。
最佳答案
将光标设置在数字值的末尾,在本例中是 -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">
关于jquery - RegEx 只有数字和单位添加退格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204587/