Reputation: 43778
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;
Upvotes: 23
Views: 532041
Reputation: 416
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/
Upvotes: 25
Reputation: 63596
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.
Upvotes: 3
Reputation: 61549
Have a look at jQuery, a cross-browser library that will make your life a lot easier.
var msg = 'abc';
$('#msg').val(msg);
$('#sp_100').attr('checked', 'checked');
Upvotes: -10
Reputation: 488534
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.
Upvotes: 5