JS: clear input on click
-Clear an input box content upon click-
One of the most used/useful functions of javascript and yet very simple to put it to work for you. The concept is simple, imagine you have an input box that displays a text like "enter your name here", once you click on it you want this text to disapear in order for you to enter your name. If you don't enter you name then the message should appear back, if you do enter your name, it should stay in the input box. Here is a live example:
1- Create the JS function on the header of your page (before the </head> tag)
<script type="text/javascript">
<!--
function cleartext(field){
if (field.defaultValue == field.value) field.value = '';
else if (field.value == '') field.value = field.defaultValue;
}
-->
</script>
2- Apply this function to the input you want (located between <body> and </body>)
<input type=text value='Enter your name here' onFocus="cleartext(this)" onBlur="cleartext(this)">
This function can be used in as many input fields you want repeating step 2 every time. The step one (declaring the function) needs to be done just once.
That's it!


Add new comment