JavaScript: 'textarea.value' not working in IE?
A few hours ago, I was instructed how to style a specific textarea with JS. The following piece of code (thanks again, Mario Menger) works like a charm in Firefox but unfortunately nothing happens in Internet Explorer (7 tested only so far).
var foo = document.getElementById('HCB_textarea');
var defaultText = 'Your message here';
foo.value = defaultText;
foo.style.color = '#888';
foo.onfocus = function(){
foo.style.color = '#000';
if ( foo.valu开发者_StackOverflow中文版e == defaultText ) {
foo.value = '';
}
};
foo.onblur = function(){
foo.style.color = '#888';
if ( foo.value == '' ) {
foo.value = defaultText;
}
};
I've already tried to replace 'value' by 'innerHTML' (for IE only) but to no effect. Any suggestions? TIA
If your script is at the top of the page, it's likely that it is running before the page has fully loaded. So the element you are trying to reference doesn't exist yet.
Internet explorer, javascript and markup just don't fit in one sentence unfortunately. Always a pain to script for it.
Anyway to debug you might try if the events get called by putting alert("onblur works!");
like lines in. Maybe alert with the value of some variables you are testing or changing.
Works fine for me. Full non-working test-case?
If you are running the page from local filesystem, make sure to allow JavaScript to run, either through the infobar, enabling ‘Allow active content to run in files on My Computer’, or adding the ‘Mark of the Web’.
You might also want to make it go grey only in the empty/defaultText case.
Edit: OK, that is one seriously vile page eBay are spitting out there, full of crazy broken content and shonky scripts. It has an ErrorHandlerManager
thing that stops your problem getting reported, as well as some other script errors on the page. Nice.
Bizarrely, eBay seem to be serving it to IE as complicated nested iframes, where Firefox gets it all on one document. Either this or the bizarre way the ‘htmlcommentbox’ script is being loaded causes your watermark script following it to be run before the comment box has been appended to the page, causing the attempt to getElementById
to fail.
I put a window.onload= function() { ... }
wrapper around your script and that made it work. I don't know if it might interfere with anything else on the page potentially using the window.onload
event though (there's too much unpleasant broken scripting to go through to check), but if so there's always addEventListener
/attachEvent
.
精彩评论