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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4067469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:20:07  来源:igfitidea点击:

Selecting all text in HTML text input when clicked

javascripthtmltextinput

提问by Questions

I have the following code to display a textbox in a HTML webpage.

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

<input type="text" id="userid" name="userid" value="Please enter the user ID" />

When the page displays, the text contains the Please enter the user IDmessage. However, I found that the user needs to click 3 times in order to select all the text (in this case it is Please enter the user ID).

当页面显示时,文本包含请输入用户 ID消息。但是,我发现用户需要单击 3 次才能选择所有文本(在本例中为Please enter the user ID)。

Is it possible to select the entire text with only one click?

是否可以一键选择整个文本?

Edit:

编辑:

Sorry, I forgot to say: I must use the input type="text"

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

回答by Boris Pavlovi?

You can use this javascript snippet:

您可以使用此 javascript 代码段:

<input onClick="this.select();" value="Sample Text" />

But apparently it doesn't work on mobile Safari. In those cases you can use:

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

<input onClick="this.setSelectionRange(0, this.value.length)" value="Sample Text" />

回答by Cory House

The previously posted solutions have two quirks:

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

  1. In Chrome the selection via .select() doesn't stick - adding a slight timeout resolves this issue.
  2. It's impossible to place the cursor at a desired point after focus.
  1. 在 Chrome 中,通过 .select() 进行的选择不会坚持 - 添加一个轻微的超时可以解决这个问题。
  2. 聚焦后不可能将光标放置在所需的点上。

Here's a complete solution that selects all text on focus, but allows selecting a specific cursor point after focus.

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

        $(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.
            });
        });

回答by oLinkWebDevelopment

Html (you'll have to put the onclick attribute on every input you want it to work for on the page)

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

 <input type="text" value="click the input to select" onclick="this.select();"/>

OR A BETTER OPTION

或更好的选择

jQuery (this will work for every text input on the page, no need to change your html):

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>

回答by Thom Porter

I know this is old, but the best option is to now use the new placeholderHTML attribute if possible:

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

<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />

This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.

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

回答by D Prinsloo

The answers listed are partial according to me. I have linked below two examples of how to do this in Angular and with JQuery.

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

This solution has the following features:

该解决方案具有以下特点:

  • Works for all browsers that support JQuery, Safari, Chrome, IE, Firefox, etc.
  • Works for Phonegap/Cordova: Android and IOs.
  • Only selects all once after input gets focus until next blur and then focus
  • Multiple inputs can be used and it does not glitch out.
  • Angular directive has great re-usage simply add directive select-all-on-click
  • JQuery can be modified easily
  • 适用于所有支持 JQuery、Safari、Chrome、IE、Firefox 等的浏览器。
  • 适用于 Phonegap/Cordova:Android 和 IO。
  • 输入获得焦点后只选择一次,直到下一次模糊然后焦点
  • 可以使用多个输入并且它不会出现故障。
  • Angular 指令具有很好的重用性,只需添加指令 select-all-on-click
  • JQuery 可以很容易地修改

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

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

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

角度: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;
      });
    }
  };
}]);

回答by Toastrackenigma

You can always use document.execCommand(supported in all major browsers)

您可以随时使用document.execCommand所有主要浏览器都支持

document.execCommand("selectall",null,false);

Selects all text in the currently focused element.

选择当前焦点元素中的所有文本。

回答by Slulego

Try:

尝试:

onclick="this.select()"

It works great for me.

这对我很有效。

回答by fyngyrz

input autofocus, with onfocus event:

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

<INPUT onfocus="this.select()" TYPE="TEXT" NAME="thing" autofocus>

This lets you open a form with the desired element selected. It works by using autofocus to hit the input, which then sends itself an onfocus event, which in turn selects the text.

这使您可以打开一个选择了所需元素的表单。它的工作原理是使用自动对焦来点击输入,然后向自己发送一个 onfocus 事件,该事件反过来选择文本。

回答by Amir Fo

Note:When you consider onclick="this.select()", At the first click, All characters will be selected, After that maybe you wanted to edit something in input and click among characters again but it will select all characters again. To fix this problem you should use onfocusinstead of onclick.

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

回答by LenArt

Indeed, use onclick="this.select();"but remember not to combine it with disabled="disabled"- it will not work then and you will need to manually select or multi-click to select, still. If you wish to lock the content value to be selected, combine with the attribute readonly.

确实,使用onclick="this.select();"但请记住不要将其与disabled="disabled"它结合使用- 届时它将无法使用,您仍然需要手动选择或多次单击以进行选择。如果要锁定要选择的内容值,请结合属性readonly