Reputation: 117
I have this code in html I want to change the checkbox check and uncheck event using javascript on some event so I am calling function ChangeCheckBox()
on button click
<div>
<label class="checkbox line">
<input type="checkbox" id="Add" />Add</label>
</div>
<script>
function ChangeCheckBox() {
var AddCheck = 0;
if (AddCheck == 1) {
document.getElementById("Add").checked = true;
} else {
document.getElementById("Add").checked = false;
}
}
</script>
So in above condition check box should unchecked but its not happening checkbox is remaining checked after running this code
Upvotes: 0
Views: 64
Reputation: 1
How do you link 'ChangeCheckBox()' to your button ? Can you post this code too ?
The problem is probably because the button refresh your page and so, the checkbox return to it initial state.
Upvotes: 0
Reputation: 31097
Since you are setting AddCheck = 0;
, of course it will not keep it's state, because you are reseting the value. If you want to simulate a toggle, here's a simpler alternative.
<script>
function ChangeCheckBox() {
var el = document.getElementById("Add");
el.checked = !el.checked;
}
</script>
Upvotes: 3