gpt4 book ai didi

jQuery : cursor automatically placed at the end with val()

转载 作者:行者123 更新时间:2023-12-01 01:26:05 25 4
gpt4 key购买 nike

我使用 JavaScript 代码来清理注册时的用户名。当不允许使用某个字符时,它将被短划线替换。

我的问题是:当用户想要在文本中间添加字符时,光标自动放置在输入的末尾

您可以在这里测试:http://jsfiddle.net/tZv5X/

HTML:

Username : <input type="text" id="username" />​

JS:

// Clean username
function clean_username(s)
{
var temp = s.replace(/[àâä@]/gi,"a");
temp = temp.replace(/[éèêë]/gi,"e");
temp = temp.replace(/[îï]/gi,"i");
temp = temp.replace(/[ôö]/gi,"o");
temp = temp.replace(/[ùûü]/gi,"u");
temp = temp.replace(/[ç]/gi,"c");
temp = temp.replace(/[. _,;?!&+'"()]/gi,"-");
return temp;
}

var current_value;
$("#username").keyup(function(e)
{
if($(this).val() != current_value)
{
$(this).val(clean_username($(this).val()));
current_value = $(this).val();
}
});​

有什么想法吗?

谢谢

最佳答案

您可以使用jCaret插件(@puppybeard 也提到过)。检查一下:

$("#username").bind({
keydown: function() {
var $this = $(this);
$this.data("pos", $this.caret().start);
},
keyup: function() {
var $this = $(this),
pos = $this.data("pos"),
value = clean_username(this.value);
if (value !== this.value) {
this.value = value;
$this.caret(pos + 1, pos + 1);
}
}
});​

演示: http://jsfiddle.net/tZv5X/3/

关于jQuery : cursor automatically placed at the end with val(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13515400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com