2

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>
1

3 Answers 3

2

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:

Sign up to request clarification or add additional context in comments.

2 Comments

ya that works. i thought this always refers to the element that it is in?
@noWayhome: It does, but your "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.
2

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

@JamesHill: If you're down-voting answers for offering no explanation, then why just this answer? Why didn't you down-vote the other answer that offered no explanation?
@xdazz, Thanks for the explanation! I learned something new today :)
1

You can also use the placeholder attribute without javascript:

<input type="text" name="the_name" placeholder="Add additional information here!">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.