gsharp gsharp - 1 year ago 75
jQuery Question

Programatically change checked of a checkbox

I have the following two checkboxes:

<input type="checkbox" id="id3"></input>
<input type="checkbox" id="id4"></input>

the desired behaviour is that when i click on id3, id4 should adopt.

that works fine for the first and second click but aftwerwards not anymore. any idea why?

here my script:

function test2()
var checked = this.checked;
$("#id4").attr("checked", "checked");


(or a working dojo here

Answer Source

Use change event(not click) and play with .prop method instead of .attr

Reason: Where both a property and an attribute with the same name exists, usually updating one will update the other, but this is not the case for certain attributes of inputs, such as value and checked: for these attributes, the property always represents the current state while the attribute (except in old versions of IE) corresponds to the default value/checkedness of the input. [Ref]

function test2() {
  $("#id4").prop("checked", this.checked);
<script src=""></script>
<input type="checkbox" id="id3">
<input type="checkbox" id="id4">