单击时选择HTML文本输入中的所有文本

Que*_*ons 515 html javascript textinput

我有以下代码在HTML网页中显示文本框.

<input type="text" id="userid" name="userid" value="Please enter the user ID" />
Run Code Online (Sandbox Code Playgroud)

页面显示时,文本中包含请输入用户ID消息.但是,我发现用户需要单击3次才能选择所有文本(在这种情况下,请输入用户ID).

只需点击一下即可选择整个文本吗?

编辑:

对不起,我忘了说:我必须使用输入 type="text"

Bor*_*vić 861

您可以使用此javascript代码段:

<input onClick="this.select();" value="Sample Text" />
Run Code Online (Sandbox Code Playgroud)

但显然它不适用于移动Safari.在这些情况下,您可以使用:

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />
Run Code Online (Sandbox Code Playgroud)

  • @DeanRadcliffe不错!我会改用`this.setSelectionRange(0,this.value.length). (40认同)
  • 在移动Safari上无法正常工作.请尝试调用this.setSelectionRange(0,9999). (12认同)
  • 为了使它更通用,你可以使用`this.id`作为click处理程序的参数.更好的是,你可以完全消除`getElementById`并将`this`作为参数传递. (9认同)
  • [我为什么要避免使用内联脚本?](http://programmers.stackexchange.com/questions/86589/why-should-i-avoid-inline-scripting) (9认同)
  • 浏览器支持的任何更新?https://www.w3schools.com/jsref/met_text_select.asp声称所有浏览器都支持它 (7认同)
  • 但是如果输入类型是数字怎么办? (3认同)
  • `onfocus` 可能是比 `onclick` 更好的选择。使用“onfocus”,它只会在您第一次单击框中时选择所有内容。使用“onclick”,每次您单击框中的某个位置时,即使您已经在框中,它也会选择所有内容。 (2认同)

Cor*_*use 62

以前发布的解决方案有两个怪癖:

  1. 在Chrome中,通过.select()选择不会粘连 - 添加一点点超时可以解决此问题.
  2. 焦点后,将光标放在所需的位置是不可能的.

这是一个完整的解决方案,可以选择焦点上的所有文本,但允许在焦点后选择特定的光标点.

        $(function () {
            var focusedElement;
            $(document).on('focus', 'input', function () {
                if (focusedElement == this) return; //already focused, return so user can now place cursor at specific point in input.
                focusedElement = this;
                setTimeout(function () { focusedElement.select(); }, 100); //select all text in any field on focus for easy re-entry. Delay sightly to allow focus to "stick" before selecting.
            });
        });
Run Code Online (Sandbox Code Playgroud)

  • 要处理用户点击该字段然后再返回的情况,请添加`.on('blur','input',function(){focusedElement = null;})` (7认同)
  • @CoryHouse没关系,因为Focus via tab本身选择了文字!不需要JavaScript. (4认同)
  • 在 Chrome 和 Firefox 中,“0”超时适用于我。不确定你的超时“50”是从哪里来的。 (2认同)

oLi*_*ent 47

Html(您必须将onclick属性放在您希望它在页面上工作的每个输入上)

 <input type="text" value="click the input to select" onclick="this.select();"/>
Run Code Online (Sandbox Code Playgroud)

或更好的选择

jQuery(这将适用于页面上的每个文本输入,无需更改您的HTML):

<script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.js"></script>  
<script type="text/javascript">
    $(function(){
        $(document).on('click','input[type=text]',function(){ this.select(); });
    });
</script>
Run Code Online (Sandbox Code Playgroud)

  • 结合焦点事件可能会更好,而不是单击那些通过表单元素选项卡的人. (22认同)
  • @Andrew这是没有必要的,因为如果您通过输入元素选项卡,则始终选择文本.;-) (7认同)
  • 除非用户已经拥有jQuery,否则更好的选择不涉及在第三方库上添加依赖项. (2认同)

Tho*_*ter 36

我知道这是旧的,但最好的选择是尽可能使用新的placeholderHTML属性:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
Run Code Online (Sandbox Code Playgroud)

除非输入值,否则将导致显示文本,从而无需选择文本或清除输入.

  • 请注意,占位符仅允许使用doctype html. (2认同)

Ami*_*ati 13

注意:当您考虑onclick="this.select()",在第一次单击时,将选择所有字符,之后可能您想在输入中编辑某些内容并再次单击字符之间,但它会再次选择所有字符。要解决此问题,您应该使用onfocus而不是onclick.


D P*_*loo 12

列出的答案是部分根据我.我在下面链接了两个如何在Angular和JQuery中执行此操作的示例.

此解决方案具有以下功能:

  • 适用于支持JQuery,Safari,Chrome,IE,Firefox等的所有浏览器.
  • 适用于Phonegap/Cordova:Android和IO.
  • 输入获得焦点后,仅选择全部一次,直到下一次模糊然后对焦
  • 可以使用多个输入,它不会出现故障.
  • Angular指令具有很好的重用性,只需添加指令select-all-on-click
  • 可以轻松修改JQuery

JQuery: http ://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p = preview

$("input").blur(function() {
  if ($(this).attr("data-selected-all")) {
  //Remove atribute to allow select all again on focus        
  $(this).removeAttr("data-selected-all");
  }
});

$("input").click(function() {
  if (!$(this).attr("data-selected-all")) {
    try {
      $(this).selectionStart = 0;
      $(this).selectionEnd = $(this).value.length + 1;
      //add atribute allowing normal selecting post focus
      $(this).attr("data-selected-all", true);
    } catch (err) {
      $(this).select();
      //add atribute allowing normal selecting post focus
      $(this).attr("data-selected-all", true);
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

Angular: http ://plnkr.co/edit/llcyAf?p = preview

var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      var hasSelectedAll = false;
      element.on('click', function($event) {
        if (!hasSelectedAll) {
          try {
            //IOs, Safari, thows exception on Chrome etc
            this.selectionStart = 0;
            this.selectionEnd = this.value.length + 1;
            hasSelectedAll = true;
          } catch (err) {
            //Non IOs option if not supported, e.g. Chrome
            this.select();
            hasSelectedAll = true;
          }
        }
      });
      //On blur reset hasSelectedAll to allow full select
      element.on('blur', function($event) {
        hasSelectedAll = false;
      });
    }
  };
}]);
Run Code Online (Sandbox Code Playgroud)


Nat*_*nna 12

我一直在寻找仅 CSS 的解决方案,发现它适用于 iOS 浏览器(经过测试的 safari 和 chrome)。

它在桌面 chrome 上没有相同的行为,但选择的痛苦并不那么大,因为作为用户你有更多的选项(双击、ctrl-a 等):

.select-all-on-touch {
    -webkit-user-select: all;
    user-select: all;
}
Run Code Online (Sandbox Code Playgroud)


Toa*_*gma 11

您可以随时使用document.execCommand(在所有主流浏览器中都支持)

document.execCommand("selectall",null,false);
Run Code Online (Sandbox Code Playgroud)

选择当前聚焦元素中的所有文本.

  • 使用 `onfocus` 时,在 Chrome 中单击输入时会选择整个页面。`onclick` 工作正常。 (2认同)

Slu*_*ego 10

尝试:

onclick="this.select()"
Run Code Online (Sandbox Code Playgroud)

这对我很有效.


fyn*_*yrz 7

输入自动对焦,具有onfocus事件:

<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>
Run Code Online (Sandbox Code Playgroud)

这使您可以打开一个选定了所需元素的表单.它的工作原理是使用自动聚焦命中输入,然后输入一个onfocus事件,然后选择文本.


Len*_*Art 6

事实上,使用onclick="this.select();"但记住不要将它与disabled="disabled"它结合- 它将不起作用,你仍然需要手动选择或多击以选择.如果要锁定要选择的内容值,请与属性组合readonly.


小智 5

你可以更换

<input type="text" id="userid" name="userid" value="Please enter the user ID" />
Run Code Online (Sandbox Code Playgroud)

和:

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
Run Code Online (Sandbox Code Playgroud)

占位符用于将值替换为您希望人们能够在文本框中键入的方式,而无需多次单击或使用 ctrl + a。占位符使它不是一个值,而是顾名思义一个占位符。这就是在多个在线表单中使用的内容,这些表单显示“此处的用户名”或“电子邮件”,当您单击它时,“电子邮件”消失,您可以立即开始输入。


小智 5

我认为通过事件来控制更好。这个变体看起来非常直观并且也可以与 ts 一起使用:

    onFocus={e => {
      e.target.select();
    }
Run Code Online (Sandbox Code Playgroud)

如果您需要每次点击都选择全部,那么您可以使用以下命令:

    onClick={e => {
      e.target.focus();
      e.target.select();
    }
Run Code Online (Sandbox Code Playgroud)