Suika Suika - 4 months ago 31
jQuery Question

Bootstrap form group checkboxes doesn't get checked in between nav pills

Here's the JSFiddle of my work: https://jsfiddle.net/pb23Ljd8/5/

I use Bootstrap nav-pills to show all products and categorized too like this:

enter image description here

And I based my checkboxes from here: http://bootsnipp.com/snippets/featured/fancy-bootstrap-checkboxes

I count the number of products checked in between the tabs like this:

jQuery(document).ready(function($) {

jQuery(".select-product").change(function() {

jQuery(".counter").text(jQuery("[type='checkbox']:checked").length);

});

});


But the glyphicon check icons doesn't appear on the second and third tabs for some reason. But when I click the products on the second and third, it increases the counter and also when I view it on the first tab, it is checked.

I just need the products to also be visibly checked on the second and third tabs and not only on the first one so it's not confusing for the user.

Ideas, anyone?

Edit: I fetch the list of products from CMS so it's dynamic. I now understand that the duplication of IDs is causing the problem.

Answer

Before we try and resolve this issues, we should break it down and see what the actual problem is.

First, let's check if we remove the content from tab 1b is the issue still present?

Nope, if we remove the checkboxes from the first tab, the checkboxes function normally on the second and third.

Fiddle #1


What if we change the id of the checkboxes (remember ids should be unique).

Notice how Book #1 now works if we change the first checkbox's id to 1a.

Fiddle #2


So now we "know" the issue is likely due to the fact that we are using checkboxes with the same id value (ref). The "issue" is now:

How do we check multiple checkboxes if one is checked

(or something like that)

Here's what I would do:

  • assign all "like" checkboxes the same class (ex. Book #1 checkboxes will have class b1)
  • use jQuery/javascript to make sure all that all "like" checkboxes, check and uncheck in unison

Working Example


EDIT

Dynamic values for the classes can be achieved by putting the IDs as classes so the similar products would match. These can be passed to JS like this assuming that $products_id_array is a PHP array that contains all the classes needed.

var productIDs = <?php echo json_encode($products_id_array) ?>;

and then creating the snippet of jQuery code on the fiddle like this

productIDs.forEach(function(val, key) {
    jQuery('.' + val).on('change', function(){
        jQuery('.' + val).prop('checked',this.checked);
    });
})
Comments