我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
我有以下代码在HTML网页中显示一个文本框。
<input type="text" id="userid" name="userid" value="Please enter the user ID" />
当页面显示时,文本包含“请输入用户ID”消息。但是,我发现用户需要单击3次才能选择所有文本(在本例中是Please enter the user ID)。
是否可以只点击一下就选择整个文本?
编辑:
抱歉,我忘了说:我必须使用input type="text"
当前回答
像这样的Html <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >
和javascript代码没有绑定
function textSelector(ele){
$(ele).select();
}
其他回答
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>
像这样的Html <input type="text" value="点击输入选择" onclick="javascript:textSelector(this)" / >
和javascript代码没有绑定
function textSelector(ele){
$(ele).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。占位符使它不是一个值,但顾名思义,它是一个占位符。这就是在许多在线表单中使用的“用户名在这里”或“电子邮件”,当你点击它时,“电子邮件”消失,你可以立即开始输入。
注意:当你考虑onclick="this.select()"时,在第一次点击时,所有字符都会被选中,之后可能你想在输入中编辑一些东西,然后再次点击字符,但它会再次选中所有字符。要解决这个问题,你应该使用onfocus而不是onclick。
现场演示
<input id="my_input" style="width: 400px; height: 30px;" value="some text to select">
<br>
<button id="select-bn" style="width: 100px; height: 30px; margin-top: 20px;cursor:pointer;">Select all</button>
<br><br>
OR
<br><br>
Click to copy
<br><br>
<input id="my_input_copy" style="width: 400px; height: 30px;" value="some text to select and copy">
<br>
<button id="select-bn-copy" style="width: 170px; height: 30px; margin-top: 20px;cursor:pointer;">Click copy text</button>
<script type="text/javascript">
$(document).on('click', '#select-bn', function() {
$("#my_input").select();
});
//click to select and copy to clipboard
var text_copy_bn = document.getElementById("select-bn-copy");
text_copy_bn.addEventListener('click', function(event) {
var copy_text = document.getElementById("my_input_copy");
copy_text.focus();
copy_text.select();
try {
var works = document.execCommand('copy');
var msg = works ? 'Text copied!' : 'Could not copy!';
alert(msg);
} catch (err) {
alert('Sorry, could not copy');
}
});
</script>