Reputation: 9797
I am looking for a way to control the default value, onfocus and onblur of textarea with JavaScript
(I know that:
- The default value in textarea is : <textarea name="text"> Default value </textarea>
- There is some solutions with html5 and with jQuery. But here I am looking for a pure JavaScript solution)
Can I have this applied to textarea?:
form name="form1" action="comprovar.php" method="post">
<input type="text" name="name" value="name"
onfocus="if (this.value=='name') this.value = '';"
onblur="if (this.value=='') this.value = 'name';"
/>
</form>
How can I get onfocus and on blur here?:
<textarea name="text"> Write here </textarea>
The example live here: http://jsfiddle.net/sKvMa/
Upvotes: 0
Views: 1319
Reputation: 4693
or you can target from jQuery like this
var mytext = $("textarea[name='text']").val();
then you could compare the text
if (mytext == 'Write here')
//do this
else
//do that
Upvotes: 0
Reputation: 66693
You can have onfocus
and onblur
on the textarea exactly like how you can from your input. See this demo: http://jsfiddle.net/sKvMa/1/
<textarea name="text"
onfocus="if (this.value=='Write here') this.value = '';"
onblur="if (this.value=='') this.value = 'Write here';" >Write here</textarea>
Upvotes: 2
Reputation: 23208
In new browsers you can use placeholder
attribute. jsfiddle
For browsers which don't support placeHolder
if( !'placeholder' in document.createElement("input") ){
var input = document.getElementsByTagName("input"),
textArea = document.getElementsByTagName("textarea");
for(var k = 0; k < input.length; k++){
input[k].value= "name";
input[k].onblur = function(){
if(this.value == "") this.value = "name"
}
input[k].onfocus = function(){
if(this.value == "name") this.value = ""
}
}
for(var k = 0; k < textArea .length; k++){
textArea [k].value= "name";
textArea [k].onblur = function(){
if(this.value == "") this.value = "name"
}
textArea [k].onfocus = function(){
if(this.value == "name") this.value = ""
}
}
}
Upvotes: 1
Reputation: 251082
You can actually achieve this without using JavaScript at all, although it is a feature of HTML5, so it works in modern browsers.
<textarea name="text" placeholder="Write here"></textarea>
Depending on what you are using the placeholder for, this may suit you as it is much simpler to implement and maintain that a scripted solution.
Upvotes: 1