Reputation: 33
I have my textarea, when it is clicked upon I would like the text to clear
<textarea id="cow" rows="5" name="message" cols="50" onfocus="clear()" >Please provide a link to an image no wider than 500px. </textarea>
and the javascript from external js file:
var cow=document.getElementById("cow").value;
function clear(){ document.getElementById("cow").value=' '; }
I realize I could probably use Jquery, but I'm just messing around trying to learn javascript.
Upvotes: 2
Views: 2241
Reputation: 816242
Believe it or not, your code is ok, apart from the fact that you named the function clear
.
Inside inline event handler, the document
object is hooked up into the event handler's scope chain, in some browsers. This has the unfortunate effect that clear
does not refer to your function, but to document.clear
. This behavior is not standardized, so depending on which browser you use, you might see different results.
If you rename your function, it works just fine: http://jsfiddle.net/QqMsX/.
You should definitely read "Is "clear" a reserved word in Javascript?", where I also explained how to avoid such situations.
Upvotes: 4
Reputation: 92274
It seems that the browser is trying to call document.clear
instead of the clear function you created. If you rename your function to clearText
, it works fine http://jsfiddle.net/7meL7/
A good way to avoid the problem is to avoid JS in attributes altogether
<textarea id="cow" rows="5" name="message" cols="50">Please provide a link to an image no wider than 500px. </textarea>
// There are better ways, but this is the simplest crossbrowser way
document.getElementById("cow").onfocus = function() {
this.value = '';
}
Upvotes: 2