[英]How to clear textarea on click?
给定一个带有默认值的<textarea>
,如下所示:
<textarea>Please describe why</textarea>
当用户单击编辑字段时如何清除默认值?
你的 JavaScript:
function clearContents(element) {
element.value = '';
}
还有你的 HTML:
<textarea onfocus="clearContents(this);">Please describe why</textarea>
我假设您想让它更健壮一点,以便在第二次聚焦时不会擦除用户输入。 这里有五篇相关的讨论和文章。
这是 David Dorward 在上面的评论中提到的(更好的)想法:
<label for="explanation">Please describe why</label>
<textarea name="explanation" id="explanation"></textarea>
您可以使用 HTML5 中引入的 placeholder 属性:
<textarea placeholder="Please describe why"></textarea>
这会将您的填充文本置于灰色,当用户单击文本字段时,该文本将自动消失。 此外,如果它失去焦点并且文本区域为空白,它将重新出现。
这是您的 javascript 文件:
function yourFunction(){
document.getElementById('yourid').value = "";
};
这是 html 文件:
<textarea id="yourid" >
Your text inside the textarea
</textarea>
<button onClick="yourFunction();">
Your button Name
</button>
尝试:
<input name="mytextbox" onfocus="if (this.value=='Please describe why') this.value = ''" type="text" value="Please Describe why">
你的意思是这样的文本字段?
<input type="text" onblur="if(this.value == '') this.value='SEARCH';" onfocus="if(this.value == 'SEARCH') this.value='';" size="15" value="SEARCH" name="xSearch" id="xSearch">
或者这个用于textarea?
<textarea id="usermsg" rows="2" cols="70" onfocus="if(this.value == 'enter your text here') this.value='';" onblur="if(this.value == '') this.value='enter your text here';" >enter your text here</textarea>
迄今为止我所知道的最佳解决方案:
<textarea name="message" onblur="if (this.value == '') {this.value = 'text here';}" onfocus="if (this.value == 'text here') {this.value = '';}">text here</textarea>
<textarea name="post" id="post" onclick="if(this.value == 'Write Something here..............') this.value='';" onblur="if(this.value == '') this.value='Write Something here..............';" >Write Something here..............</textarea>
jQuery 属性 val() 应该可以完成这项工作。 你可以这样做$('#YourTextareaID').click(function(e) { e.target.value = ''; })
。
你可以试试这个代码,
<textarea name="textarea" cols="70" rows="2" class="searchBox" id="textarea" onfocus="if(this.value == 'Please describe why') this.value='';" onblur="if(this.value == '') this.value='Please describe why';">Please describe why</textarea>
如果您有来自数据库的动态数据,这是一个解决方案......
'data' 变量代表数据库数据。
如果尚未保存数据,则将显示占位符。
一旦用户开始输入,占位符将消失,然后他们可以输入文本。
希望这可以帮助某人!
// If data is NOT saved in the database
if (data == "") {
var desc_text = "";
var placeholder = "Please describe why";
// If data IS saved in the database
} else {
var desc_text = data;
var placeholder = "";
}
<textarea placeholder="'+placeholder+'">'+desc_text+'</textarea>
不需要脚本。 您可以使用onblur
和onfocus
结合placeholder
使文本消失并出现在textarea 上。
<textarea onblur="this.placeholder='Write something..'" onfocus="this.placeholder=''" placeholder="Write something.." name="" cols="40" rows="4"></textarea>
<textarea onClick="javascript: this.value='';">Please describe why</textarea>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.