如何使用 jQuery 验证将光标放置在输入字段的末尾?

发布于 2024-11-17 03:29:37 字数 354 浏览 5 评论 0原文

我试图在验证后将光标放置在输入字段的末尾。这工作正常,除非您输入太多字母(超过输入框的默认长度),最后一个字母不会显示,因为输入的值在清理后被重写。

如何修改此代码以将光标置于输入字段的末尾?

在 html 中:

<input type="text" id="myInput">

在 jQuery 中:

$("#myInput").keyup(
   function(){
      this.value = this.value.replace(/[^a-z]/gi,''); // only letters
   }
);

I am trying to place the cursor at the end of the input field after validation. This works fine, except if you type too many letters (more than the default length of the input box), the last letters do not show, because the value of the input is rewritten after the sanitization.

How can I modify this code to put the cursor at the end of the input field?

In the html:

<input type="text" id="myInput">

In the jQuery:

$("#myInput").keyup(
   function(){
      this.value = this.value.replace(/[^a-z]/gi,''); // only letters
   }
);

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

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

发布评论

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

评论(1

放低过去 2024-11-24 03:29:37

不要在 keyup 事件中进行验证,而是尝试使用 keydown 事件,因为事件触发时字符尚未添加到输入字段。

你可以做这样的事情......

$elem.keydown(function (e) {
    if (isDisallowed(e.which)) {
        e.preventDefault();
        $('#errorMsg').text('That key is not allowed').delay(2000).fadeOut();
    }
});

Instead of validating in the keyup event, try using the keydown event as the character is not yet added to the input field when the event is fired.

You can do something like this...

$elem.keydown(function (e) {
    if (isDisallowed(e.which)) {
        e.preventDefault();
        $('#errorMsg').text('That key is not allowed').delay(2000).fadeOut();
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文