jQuery .focus()突出显示所有预填充文本

时间:2022-11-03 08:25:12

HTML

HTML

<input id="formloginusername" type="text" name="username" placeholder="Username" value="Pre-filled-from-database"></input>

JS:

JS:

$(document).ready(function() {
    $("#formloginusername").focus();
});

Problem:

问题:

The text "Pre-filled-from-database" is highlighted. I only want the cursor to show in the field as if the user had clicked it after the filled text.

突出显示“预填充数据库”文本。我只希望光标在字段中显示,就像用户在填充文本后点击它一样。

Thanks!

谢谢!

3 个解决方案

#1


14  

Here's a nifty little trick...

这是一个漂亮的小技巧......

$(document).ready(function() {
    var $field = $("#formloginusername"),
        oldVal = $field.val();
    $field.focus().val('').val(oldVal);
});

DEMO: http://jsfiddle.net/X7Y8S/

演示:http://jsfiddle.net/X7Y8S/

#2


0  

Just this will do:

这样做会:

$('#field').focus().val($("#field").val());

#3


0  

Hopstream, what I found in Chrome using your method is the cursor ended up at the end of the text. I needed a way to get the cursor focused on the start of the field without highlighting the text. This worked for me:

Hopstream,我在Chrome中使用您的方法找到的是光标最终在文本末尾。我需要一种方法来将光标聚焦在字段的开头而不突出显示文本。这对我有用:

$('#ElementID').each(function () { $(this).focus(); this.selectionEnd = this.selectionStart; });

$('#ElementID')。each(function(){$(this).focus(); this.selectionEnd = this.selectionStart;});

#1


14  

Here's a nifty little trick...

这是一个漂亮的小技巧......

$(document).ready(function() {
    var $field = $("#formloginusername"),
        oldVal = $field.val();
    $field.focus().val('').val(oldVal);
});

DEMO: http://jsfiddle.net/X7Y8S/

演示:http://jsfiddle.net/X7Y8S/

#2


0  

Just this will do:

这样做会:

$('#field').focus().val($("#field").val());

#3


0  

Hopstream, what I found in Chrome using your method is the cursor ended up at the end of the text. I needed a way to get the cursor focused on the start of the field without highlighting the text. This worked for me:

Hopstream,我在Chrome中使用您的方法找到的是光标最终在文本末尾。我需要一种方法来将光标聚焦在字段的开头而不突出显示文本。这对我有用:

$('#ElementID').each(function () { $(this).focus(); this.selectionEnd = this.selectionStart; });

$('#ElementID')。each(function(){$(this).focus(); this.selectionEnd = this.selectionStart;});