I would like my script to check the textarea box when a user clicks on it and if it has the value "Add additional information here!" to make the box blank and change the text color to #000. it starts out as grey.
javascript
function changeMessage() {
if(this.value=='Add additional information here!')
{this.value='';this.style.color='#000';}
}
HTML
<textarea name="message" id="message_input" rows="4" cols="21" maxlength="200"
onfocus="changeMessage();"
onblur="changeMessageBack();"
>Add additional information here!</textarea>
-
This question is similar to: How does the "this" keyword work, and when should it be used?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem.dumbass– dumbass2024年10月08日 15:16:58 +00:00Commented Oct 8, 2024 at 15:16
3 Answers 3
In the context of changeMessage(), this does not refer to your text area. Try passing in your text area object like this:
JS:
function changeMessage(obj) {
if(obj.value=='Add additional information here!') {
obj.value='';
obj.style.color='#000';
}
}
HTML
<textarea name="message" id="message_input" rows="4" cols="21" maxlength="200"
onfocus="changeMessage(this);"
onblur="changeMessageBack(this);"
>Add additional information here!</textarea>
Here's a working fiddle to demonstrate.
Additional Information:
2 Comments
"changeMessage(this);" becomes the body of an anonymous function, so it's in that function that this refers to the element. When you invoke a function from inside another, JavaScript doesn't automatically set this in the function you're invoking to the current value. You need to do that manually. The answer from @xdazz shows how.When you called changeMessage() in global scope, the this refers the window object, while you can tell the runtime the value of this provided for the call to function by use .call.
Change onfocus="changeMessage();" to onfocus="changeMessage.call(this);"
2 Comments
You can also use the placeholder attribute without javascript:
<input type="text" name="the_name" placeholder="Add additional information here!">