I want to change of status of an input checkbox when click on another element.
But click triggers only once that code block.
#menu-state:checked {
background: red;
}
#menu-state {
background: blue;
}
<input type="checkbox" id="menu-state" class="menu-state">
<a href="#menu-state" role="button" class="menu-anchor menu-anchor-open"
id="menu-anchor-open"></a>
$("#menu-anchor-open").on("click", function (e) {
e.preventDefault()
if ($('#menu-state').prop('checked')) {
$('#menu-state').attr('checked', false);
} else {
$('#menu-state').attr('checked', true);
}
});
In first click, it adds checked="checked" on the input, but on another clicks, it doesnt work.
I have also tried those solutions too;
Changing a checkbox's state programmatically in dashcode
Checkbox click function is not working
Setting "checked" for a checkbox with jQuery
jquery check all input:checkbox on button click
What am i missing?
For example below works on every click. But previous one doesnt work.
$("#menu-anchor-open").on("click", function (evt) {
evt.preventDefault()
if ($('#menu-state').hasClass('open')) {
$('#menu-state').removeClass('open');
} else {
$('#menu-state').addClass('open');
}
});