You are here: html css » to clear a textarea when it gains focus
To clear a textarea when it gains focus
- Written By
- Shadow
- Submitted At
- 2009-08-28 11:37:51
- Num Views
- 1494
- Category
- HTML / CSS
|
The code I used: <textarea rows="10" cols="40" name="comments">Write your comments here</textarea> I know that it should only clear my text, incase it loses focus and gains it again after it was typed in.. ??? By Shadow @ 2009-08-28 11:37:51
|
|
There's a few ways you can do this with JS frameworks like JQuery and others but we'll just do plain JS for now. Even though some say JQuery is easier, which it is, it is always good to know Javascript itself first. So what you do is add the onfocus parameter to your textarea to call a function which will do all the work. <textarea rows="10" cols="40" onfocus="clearText(this);" onblur="writeText(this);" name="comments">Write your comments here</textarea> We are passing the textarea element to the function as a parameter so we can manipulate the element without having to assign an ID to it. Now lets create the function clearText and writeText. The clearText function gets the element in as a parameter called myTextArea. It then checks if the value is 'Write your comments here' as we do not want to clear something the user has already typed. If the value is 'Write your comments' here we know the user has not typed anything and we clear the value of the textarea by setting the value to nothing. This takes care of the clearing, however if a user focuses on an element and does not type anything and then leaves the element - onblur (opposite of onfocus), we want the message to come back so that they know what needs to go inside the box. This is what writeText does. The writeText function also takes our textarea element in as a parameter we then test the value to see if the user has typed anything in the box by checking if it is empty or not. If it is empty that means the user has not typed in anything and we write the 'Write your comments here' text into the box again. This way it will always say 'Write your comments here' until the user has actually typed anything in the box. <script type="text/javascript"> function clearText(myTextArea){ if(myTextArea.value == 'Write your comments here'){ myTextArea.value = ''; } } function writeText(myTextArea){ if(myTextArea.value == ''){ myTextArea.value = 'Write your comments here'; } } </script> By PHPin24 @ 2009-08-30 10:34:52
|
|
Yip! That does it! Works even better than I hoped.. ;D THANKS By Shadow @ 2009-08-30 11:16:40
|
