Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 860
bouncingHippo Avatar asked May 25 '26 05:05

bouncingHippo


1 Answers

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>
like image 173
Travis J Avatar answered May 27 '26 18:05

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!