我创建了一些输入字段,我正在清理用户输入字段。
所以,我正在使用按键检测事件,例如.keyup()
这一切都运作良好,但我注意到有一件事对用户来说很烦人。
当脚本在键入时清理数据时,它们的光标将被发送到输入字段的末尾。
所以,如果你想编辑值的中间部分,你的光标会立即转到框的末尾。
有没有人知道如何在输入字段内保持光标的当前位置?
我没有屏住呼吸,但我想我会问。
这是我正在使用的清理代码:
$(".pricing").keyup(function(){
// clean up anything non-numeric
**var itemprice = $("#itemprice").val().replace(/[^0-9\.]+/g, '');**
// return the cleaner value back to the input field
**$("#itemprice").val(itemprice);**
});
答案 0 :(得分:3)
如果我可以提出建议,可能会有更优雅的解决方案。根本不允许输入非数字键:
**允许我修改,这个功能应该比之前发布的功能更好:
$(".pricing").keypress(function(event) {
// disallow anything non-numeric
var nonNumeric = /[0-9\.]+/g;
var key = String.fromCharCode(event.which);
if (!(key == '' || nonNumeric.test(String.fromCharCode(event.which)) || event.which == 8 || event.which == 13)) {
return false;
}
});
当然,你可能想稍微调整一下,但这应该让你开始。
此外,如果您担心上面所说的dclowd9901,您可以显示一条验证消息,指出不允许使用非数字条目,而不是简单地吞下击键。
答案 1 :(得分:0)
在修改值之前,您需要存储插入位置,然后将其恢复。这可能涉及一些计算以确定在删除某些字符后它应该在何处结束,但是您可以在基本工作完成后对其进行微调。这是first hit on Google for jQuery caret positioning。
答案 2 :(得分:0)
首先,我建议切换到keydown。它会更快地清理输入。否则,在某些浏览器中,文本将显示然后快速消失。附加到keydown可以防止这种情况发生。
$(".pricing").keydown(function(){
// clean up anything non-numeric
var cursor = getCaretPosition($("#itemprice"));
**var itemprice = $("#itemprice").val().replace(/[^0-9\.]+/g, '');**
// return the cleaner value back to the input field
**$("#itemprice").val(itemprice);**
setCaretPosition($("#itemprice"), cursor)
});
function GetCaretPosition (ctrl) {
var CaretPos = 0;
if (document.selection) { // IE
ctrl.focus ();
var Sel = document.selection.createRange ();
var Sel2 = Sel.duplicate();
Sel2.moveToElementText(ctrl);
var CaretPos = -1;
while(Sel2.inRange(Sel))
{
Sel2.moveStart('character');
CaretPos++;
}
}
else if (ctrl.selectionStart || ctrl.selectionStart == '0') { // Others
CaretPos = ctrl.selectionStart;
}
return (CaretPos);
}
function setCaretPosition(elem, caretPos) {
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
另外,为什么不在您的函数中引用$(this)
而不是#itemprice
中的硬编码
答案 3 :(得分:0)
我推荐使用jQuery字母数字插件:http://www.itgroup.com.ph/alphanumeric/