[javascript] document.getElementById().value and document.getElementById().checked not working for IE

I tried to assign a new value into the hidden input and checkbox of an input form. It's working fine in Firefox but not in IE (I'm using IE 7). Does anyone know what is wrong with my code?

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp_100">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp_100').checked = true;

This question is related to javascript

The answer is


The code you pasted should work... There must be something else we are not seeing here.

Check this out. Working for me fine on IE7. When you submit you will see the variable passed in the URL.


For non-grouped elements, name and id should be same. In this case you gave name as 'sp' and id as 'sp_100'. Don't do that, do it like this:

HTML:

<input type="hidden" id="msg" name="msg" value="" style="display:none"/>
<input type="checkbox" name="sp" value="100" id="sp">

Javascript:

var Msg="abc";
document.getElementById('msg').value = Msg;
document.getElementById('sp').checked = true;

For more details

please visit : http://www.impressivewebs.com/avoiding-problems-with-javascript-getelementbyid-method-in-internet-explorer-7/


Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.

Thus you may have issues due to your variable name.

Try this and see if it works.

var someOtherName="abc";
//  ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;

There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.

Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.