bouncingHippo
bouncingHippo

Reputation: 6040

changing ''checked' attribute of a checkbox using javascript

right now when it first loads the html page, my checkbox was created in this way:

<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>

in a function in on the same html:

boolean checked = true;
document.theForm.elements['CBOX1'].checked = true;

For some reason, the checked box value is not checked when the function is called later on the page. Is it because when i first created the checkbox, i created it without a 'checked' attribute? And then when i assign it a value, the element doesnt seem to include the checked attribute anymore as when i check on the source of the page. its still the same...

<input type="checkbox" id="CBOX1" name="CBOX1" onclick="onCBOX(this)" disabled/>

For simplicity sake, i know for sure that there were changes made to other attributes of this element using AJAX, but i am at a loss to WHY the checked attribute is not carried over... What's the alternative?

Upvotes: 2

Views: 58369

Answers (3)

Travis J
Travis J

Reputation: 82277

Check the checkbox:

document.theForm.elements['CBOX1'].checked = true;
document.theForm.elements['CBOX1'].checked = "checked"; 

Uncheck the checkbox:

document.theForm.elements['CBOX1'].checked = false; 

If you want it unchecked on load then don't touch it, by default it is unchecked.

Moreover, no click events will be registered if you use the disabled attribute on your input field.

See this jsfiddle for an example.

EDIT

If clickability is not the issue then just do what I already pointed out. Here is a full working example.

<html>
 <head>
 </head>
 <body>
  <input id="tar" type="checkbox" disabled />
  <input type="checkbox" onclick="callFunc(this)" />
  <script type="text/javascript">
   function callFunc(elem){
    document.getElementById("tar").checked = elem.checked;
   }
  </script>
 </body>
</html>

Upvotes: 7

Uchenna Nwanyanwu
Uchenna Nwanyanwu

Reputation: 3204

Try this, not tested anyway.

document.theForm.elements['CBOX1'].checked = true; 

Upvotes: 0

D&#39;Arcy Rittich
D&#39;Arcy Rittich

Reputation: 171411

Try setting it to true instead:

document.theForm.elements['CBOX1'].checked = true; 

Upvotes: 0

Related Questions