jQuery .focus() is highlighting all pre-filled tex

2019-01-28 02:59发布

HTML

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

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条回答
forever°为你锁心
2楼-- · 2019-01-28 03:37

Just this will do:

$('#field').focus().val($("#field").val());
查看更多
男人必须洒脱
3楼-- · 2019-01-28 03:50

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/

查看更多
手持菜刀,她持情操
4楼-- · 2019-01-28 03:53

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:

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

查看更多
登录 后发表回答