0

This is my code:

$('#opentab').click(function() {
    $('.opentabdiv').toggle();
    $(this).toggleClass("closetab opentab");
    return false;
});

Basically there is a DIV (or link I should say) called #opentab" that when it is clicked, another DIV called .opentabdiv will open, and the class of #opentab will change.

Now my problem comes when I put a checkbox in the #opentab DIV. I want the checkbox to be checked when the .opentabdiv is open, and empty when it is closed.

This is the HTML of the checkbox inside the #opentab DIV:

<a href="#" id="opentab" class="closetab"><input type="checkbox" id="yesactive" name="yesactive" value="yes"> OPEN</a>

Does anyone know the jquery to make the checkbox change? I've tried some codes I found but it only works once. If I close the DIV, it does not untick.

The checkbox should be unticked on default because the .opentabdiv DIV is closed.

  • possible duplicate of [How do I check a checkbox with jQuery?](http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery) – Ram Jan 12 '14 at 10:19
  • I'm not checking to see if it is checked. I am making the checkbox checked (ticked). – Flare Hocke Jan 12 '14 at 10:22
  • Have you checked the linked question? It **does** answer your question. – Ram Jan 12 '14 at 10:23
  • It works when I click on the #opentab DIV now, but when I click the checkbox itself it still won't change... – Flare Hocke Jan 12 '14 at 10:35

1 Answers1

1

You can use .prop() method and :visible selector:

$('#opentab').on('click', function() {
    var $t = $('.opentabdiv').toggle();
    $(this).toggleClass("closetab opentab");
    $('#yesactive').prop('checked', $t.is(':visible'));
    return false;
});

$('#yesactive').on('click', function(e) {
   // Stop the propagation of the event 
   // for preventing bubbling 
   e.stopPropagation();
});
Ram
  • 143,282
  • 16
  • 168
  • 197