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

杀马特。学长 韩版系。学妹 提交于 2020-01-10 05:06:47

问题


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!


回答1:


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/




回答2:


Just this will do:

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



回答3:


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; });



来源:https://stackoverflow.com/questions/13371430/jquery-focus-is-highlighting-all-pre-filled-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!