0

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');
        }
    });
Under Voltage
  • 23
  • 1
  • 5
  • Its something else. I just stuck your code ina snippet and it works fine – Kinglish Sep 11 '22 at 19:21
  • 1
    As above: https://jsfiddle.net/hs58Ly6o/ – Rory McCrossan Sep 11 '22 at 19:25
  • i use webpack mix on laravel. and it compiles my javascript file into app.js file. Can be it related with this problem? Because it compiles jquery and custom js code into one file. But still, i dont know what is the problem. because addClass and removeClass work on calling onclick function. – Under Voltage Sep 11 '22 at 19:35
  • meh, i solved the problem. there was an another element which closes and overrides the menu-anchor-open class. That is why it doesnt work. Really appreciate for helps. – Under Voltage Sep 11 '22 at 19:52

0 Answers0