0

How to remove a class if already exists by using toggleClass

$('.mobile_billing').toggleClass('open');

I've a scenario where we use above code to expand and collapse the accordion. There are two options to collapse and expand:

  1. From Accordion arrow

  2. From Check BOX.

When user clicks on Check Box and Accordion is already expanded No action is required. Where as if Accordion is in Collpase state, would like to open it.

I tried above code, it either opens or close. It doesn't check if already open. Can someone please help

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
Nil Pun
  • 17,035
  • 39
  • 172
  • 294

3 Answers3

1

You need to write two seperate events for checkbox and accordian

suppose checkbox id=checkbox

$("#checkbox").click(function(){      
   if(!$('.mobile_billing').hasClass('open')) // it checks if mobile_billing is not open
     $('.mobile_billing').addClass('open');
});

And suppose accordian has id=accordian

 $("#accordian").click(function(){

         $('.mobile_billing').addClass('open');
 });
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57
0

When click on the checkbox check for the Accordion is open or not if if is in open state return from the function. otherwise do toggle action.

$('#checkboxId').on('click',function(){
  if($('.mobile_billing').hasClass('open')) return;

  $('.mobile_billing').toggleClass('open');
})
chandu
  • 2,276
  • 3
  • 20
  • 35
0

You can do:

$( '.accordion_checkbox' ).click( function() { 
  $( '.mobile_billing' ).toggleClass( 'open', this.checked );
});

So 'open' only gets added when the checkbox is checked and removed when it's unchecked by the user. It's irrelevant whether it's open already when the user clicks on the checkbox; it'll just stay open. This is using jQuery.toggleClass's switch option and checking the checked (boolean) value of the checkbox you've attached the click event to.

Community
  • 1
  • 1
roobeedeedada
  • 511
  • 4
  • 11