javascript/jquery 输入字段清理

发布于 2024-08-27 14:38:25 字数 547 浏览 6 评论 0原文

我创建了一些输入字段,当用户键入时我正在清理这些输入字段。

因此,我正在使用击键检测事件,例如 .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);**

});

I've created a few input fields, that I am cleaning up as the user types.

So, I'm using a keystroke detection event, like .keyup()

It's all working very well, but I do notice one thing that's rather annoying for the users.

While the script is cleaning the data as they type, their cursor is being sent to the end of the input field.

So, if you want to edit the middle of the value, you're cursor immediately goes to the end of the box.

Does anyone know of a way to maintain the cursor's current position inside the input field?

I'm not holding my breath, but I thought I'd ask.

Here's the cleanup code I'm using:

$(".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);**

});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

贪恋 2024-09-03 14:38:25

如果我可以提出建议,可能会有更优雅的解决方案。只需完全禁止输入非数字键即可:

**请允许我修改一下,此功能应该比之前发布的功能更好:

    $(".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 上面所说的内容,您可以显示一条验证消息,指出不允许非数字输入,而不是简单地吞下击键。

If I could make a suggestion, there might be a more elegant solution. Simply disallow non-numeric keys to be entered at all:

**Allow me to revise, this function should work better than the one previously posted:

    $(".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;
        }
    });

Of course, you'll probably want to fine tune a bit but this should get you started.

Also, if you're concerned about what dclowd9901 said above, you could display a validation message saying that non-numeric entries are not allowed, rather than simply swallowing the keystroke.

我的影子我的梦 2024-09-03 14:38:25

您需要在修改值之前存储插入符号位置并在修改后恢复它。这可能需要一些计算来确定删除一些字符后应该在哪里结束,但是您可以在基础知识工作后对其进行微调。这是Google 上首次出现的 jQuery 插入符定位

You'll need to store the caret position before modifying the value and restore it afterwards. This might involve some calculations to determine where it should end up after deleting some characters, but you can fine-tune that after you get the basics working. Here's the first hit on Google for jQuery caret positioning.

把昨日还给我 2024-09-03 14:38:25

首先,我建议切换到 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 中进行硬编码

First of all, I'd recommend switching to keydown. It'll clean the input faster. Otherwise in some browsers the text will show up then disappear quickly. Attaching to keydown prevents that.

$(".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();
        }
    }
}

Also, why not reference $(this) in your function instead of hard coding in #itemprice

人间不值得 2024-09-03 14:38:25

我推荐 jQuery 字母数字插件: http://www.itgroup.com.ph/alphanumeric/

I recommend jQuery alphanumeric plugin: http://www.itgroup.com.ph/alphanumeric/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文