什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?


当前回答

我知道这里已经有很多答案了——但这一个到目前为止还没有找到;一个解决方案,也与ajax生成的内容:

$(function (){
    $(document).on("focus", "input:text", function() { 
        $(this).select(); 
    });
});

其他回答

这也适用于iOS:

<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

我有点晚了,但这在IE11, Chrome, Firefox中工作完美,没有混乱的鼠标(没有JQuery)。

inputElement.addEventListener("focus", function (e) {
    var target = e.currentTarget;
    if (target) {
        target.select();
        target.addEventListener("mouseup", function _tempoMouseUp(event) {
            event.preventDefault();
            target.removeEventListener("mouseup", _tempoMouseUp);
        });
    }
});
$(document).ready(function() {
    $("input:text")
        .focus(function () { $(this).select(); } )
        .mouseup(function (e) {e.preventDefault(); });
});
$(document).ready(function() {
  $("input[type=text]").focus().select();
});

我知道内联代码是不好的风格,但我不想把它放在.js文件中。 不用jQuery也能工作!

<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>