开发者

Erasing the contents of an input / textarea when it's clicked?

to make editing of these fields easier, I'd be nice if their contents were deleted when they're clicked. Also, the default value (presented ini开发者_StackOverflow社区tially) needs to be submitted if it hasn't changed, this means I'm (probably) not looking for a(n HTML 5) placeholder which gets erased automatically, but actual text. Would be even better if the default value would return if the field is deselected and left blank.

Any suggestions?

P.S: Example: the "your email" input at the top of http://www.makeuseof.com/.


<input type="text" value="Something" onfocus="if (this.value == this.defaultValue) this.value='';" onblur="if (this.value == '') this.value = this.defaultValue;">

If you want to use it in more than one element, you should extract the event handlers to an external function/script.

EDIT:

When using an external function, you'll need to provide a reference to the input element as a parameter to the function.

<script type="text/javascript">
    function focused(element){if (element.value == element.defaultValue) element.value='';}
    function blurred(element){if (element.value == '') element.value = element.defaultValue;}
</script>

<input type="text" value="Default Value" onfocus="focused(this)" onblur="blurred(this)">

NB: In JavaScript it is convention to have functions start with a small letter.


Try it with onfocus:

<input type="text" value="Default text" onfocus="this.value = ''">
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜