Javascript 如何使用javascript清除文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4135818/
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
How to clear a textbox using javascript
提问by kalls
I have a
我有一个
<input type="text" value="A new value">
I need a javascript method to clear the value of the textbox when the focus is on the textbox.
当焦点位于文本框上时,我需要一个 javascript 方法来清除文本框的值。
How can this be achieved?
如何做到这一点?
采纳答案by Colin O'Dell
It sounds like you're trying to use a "watermark" (a default value that clears itself when the user focuses on the box). Make sure to check the value before clearing it, otherwise you might remove something they have typed in! Try this:
听起来您正在尝试使用“水印”(当用户关注框时会自行清除的默认值)。确保在清除之前检查该值,否则您可能会删除他们输入的内容!尝试这个:
<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';">
That will ensure it only clears when the value is "A new value".
这将确保它仅在值为“新值”时清除。
回答by zish
just get element using
只需使用
function name()
{
document.getElementById('elementid').value = "";
}
you can call this function on onfocus event of textbox and clear the value
您可以在文本框的 onfocus 事件上调用此函数并清除值
回答by KeatsKelleher
<input type="text" value="A new value" onfocus="javascript: if(this.value == 'A new value'){ this.value = ''; }" onblur="javascript: if(this.value==''){this.value='A new value';}" />
回答by G Rice
For those coming across this nowadays, this is what the placeholder
attribute was made to do. No JS necessary:
对于现在遇到这种情况的人来说,这就是该placeholder
属性的用途。不需要JS:
<input type="text" placeholder="A new value">
回答by Sashi
Simple one
简单的
onfocus="javascript:this.value=''" onblur="javascript: if(this.value==''){this.value='Search...';}"
回答by Sajeeb
use sth like
使用某事
<input type="text" name="yourName" placeholder="A new value" />
<input type="text" name="yourName" placeholder="A new value" />
回答by SwapnilP
just set empty string
只需设置空字符串
<input type="text" id="textId" value="A new value">
document.getElementById('textId').value = '';
回答by Justin Ethier
回答by Lucky13
Give this in input tag of textbox:
在文本框的输入标签中给出这个:
onClick="(this.value='')"
回答by AlexV
Use the onfocus and onblur events like this:
像这样使用 onfocus 和 onblur 事件:
<input type="text" name="yourName" value="A new value" onfocus="if (this.value == 'A new value') this.value = '';" onblur="if (this.value == '') this.value = 'A new value';">