dimanche 18 juin 2017

jQuery - Click checkbox add class and remove class

I am using bootstrap to create a checkbox and I want to create a checkbox that clicks on all checkboxes and vice versa (I know there are a lot of guides in stackoverflow about this) but in all it only works on the inputs.

In this case I am enclosing the input with a label "label", when activating the checkbox bootstrap automatically adds the "active" class to this tag that causes the "check" to appear. When I tried to implement scripts found here that added the "checked" attribute to the input of the checkbox, they did not work for this very reason so I tried the following:

$('label#seleccionartodos').click(function(){
  $('input.videoscheck').prop('checked', true).parent().addClass('active');
}); 

And this is my html:

<div class="form-group" data-toggle="buttons">
<label for="selectall">SELECT / UNSELECT ALL:</label>
<label class="btn btn-success" id="seleccionartodos">
  <input type="checkbox" id="selectall" autocomplete="off">
  <span class="glyphicon glyphicon-ok"></span>
</label>
</div>
<div class="form-group" data-toggle="buttons">
  <label class="btn btn-success">
    <input type="checkbox" class="videoscheck" autocomplete="off">
    <span class="glyphicon glyphicon-ok"></span>
  </label>
 </div>
 <div class="form-group" data-toggle="buttons">
  <label class="btn btn-success">
    <input type="checkbox" class="videoscheck" autocomplete="off">
    <span class="glyphicon glyphicon-ok"></span>
  </label>
 </div>
 <div class="form-group" data-toggle="buttons">
  <label class="btn btn-success">
    <input type="checkbox" class="videoscheck" autocomplete="off">
    <span class="glyphicon glyphicon-ok"></span>
  </label>
 </div>

This works halfway, when I click the checkbox, add the "checked" attribute to all the checkboxes with the ".videoscheck" class and also adds the "active" class to the parent tag that encloses them.

But since I'm not good with jQuery, I do not know how to do it so that when I click it again, all other checkboxes will be deselected (that is, the opposite of the initial action).

Here's a Fiddle showing what I'm exposing.




Aucun commentaire:

Enregistrer un commentaire