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

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

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

是否可以只点击一下就选择整个文本?

编辑:

抱歉,我忘了说:我必须使用input type="text"


当前回答

以下是Shoban回答的可重复使用版本:

<input type="text" id="userid" name="userid"
 value="Please enter the user ID" onfocus="Clear(this);"
/>

function Clear(elem)
{
elem.value='';
}

这样就可以为多个元素重用clear脚本。

其他回答

当.select()在移动平台上不起作用时,这个问题有选项:在iOS设备(移动Safari)上以编程方式选择输入字段中的文本

Html(你必须把onclick属性放在你想要它在页面上工作的每个输入上)

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

或者一个更好的选择

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>

你可以使用文档。execCommand(所有主要浏览器都支持)

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

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


更新2021:execCommand现在已弃用。

说实话,这可能是最好的选择,因为它是一个老的IE API,已经被其他浏览器采用了,使用它总是有点奇怪。尽管如此,有一个解决方案可以同时处理<input>字段和可满足元素就很好了。

.select()可能是目前<input>字段的最佳方式。

对于contenteditable,现代的解决方案是使用range API。

Try:

onclick="this.select()"

这对我来说很有效。

你可以替换

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

:

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

占位符用来替换值,就像你希望人们能够在文本框中键入而无需多次单击或使用ctrl + a。占位符使它不是一个值,但顾名思义,它是一个占位符。这就是在许多在线表单中使用的“用户名在这里”或“电子邮件”,当你点击它时,“电子邮件”消失,你可以立即开始输入。