Issue with Bootstrap form group checkboxes not being checked when switching between Nav Pills

Check out my work on JSFiddle: https://jsfiddle.net/pb23Ljd8/5/

I've utilized Bootstrap nav-pills to display all products and categorize them like this:

https://i.sstatic.net/oQxTk.png

The checkboxes are based on this design:

To keep track of the checked products in each tab, I have implemented the following code:

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

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

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

  });

});

However, there seems to be an issue with the glyphicon check icons not showing up on the second and third tabs. Despite this, the counter increments correctly when selecting products from these tabs. The challenge lies in ensuring that the products are visually checked across all tabs for a seamless user experience.

Any suggestions on how to achieve this?

Edit: It's worth mentioning that the product list is dynamically fetched from CMS, which might be contributing to the problem due to ID duplication.

Answer №1

Let's break down the issue before attempting to resolve it and pinpoint the exact problem.

To start, we should investigate if removing the content from tab 1b eliminates the problem.

Upon testing, we found that removing the checkboxes from the first tab allows the checkboxes on the second and third tabs to function correctly.

Check out Fiddle #1 for reference


Another approach could be changing the id of the checkboxes (keeping in mind that ids must be unique).

If we modify the id of the first checkbox to 1a, we can see that now Book #1 is functioning properly.

Explore Fiddle #2 for more details


It appears that the issue stems from using checkboxes with identical id values (source). The current challenge is:

How do we synchronize checking multiple checkboxes when one is selected?

(or something along those lines)

A potential solution would involve:

  • Assigning similar checkboxes the same class (e.g., checkboxes for Book #1 could have class b1)
  • Using jQuery or JavaScript to ensure all related checkboxes behave consistently

See Working Example here


UPDATE

To dynamically assign classes based on IDs for matching products, you can pass PHP arrays like $products_id_array as follows:

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

You can then include a snippet of jQuery code in the fiddle:

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

Answer №2

Check out this JavaScript code snippet at this link. It's designed to be effective.

 jQuery(".select-product").change(function() {
      var checkValue = jQuery(this).prop('checked');
      $('.select-product#' + jQuery(this)[0].id).each(function() {
          if (checkValue == true) {
              jQuery(this).prop('checked', true)
          } else {
              jQuery(this).prop('checked', false);
          }
      });
      var uniqueId = [];
      jQuery("[type='checkbox']:checked").each(function() {
          uniqueId.push(jQuery(this)[0].id);
      });


      Array.prototype.getUnique = function() {
          var u = {},
              a = [];
          for (var i = 0, l = this.length; i < l; ++i) {
              if (u.hasOwnProperty(this[i])) {
                  continue;
              }
              a.push(this[i]);
              u[this[i]] = 1;
          }
          return a;
      }
      jQuery(".counter").text(uniqueId.getUnique().length);          
  });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a for loop in PHP and the jQuery show/hide method can dynamically display a corresponding number of div elements based on the number

I've used PHP to create a loop that generates divs based on the number of buttons pressed. <?php for ($x = 1; $x <= 6; $x++) { ?> <button type="button"> <span><?php echo $x; ?></span> </button> ...

What is the best way to transfer an excel file to a server using AngularJS in a Django project?

I am experiencing an issue with uploading a file to the server. The variable files in the for loop is showing up as undefined during debugging. Please review the directive to ensure it is correct. HTML <input type="file" accept=".xlsx" file-model/> ...

Encoding large files using the Base64 format

Is there a method to encode a file of, say, 2 gigabytes without splitting it into chunks? I am encountering errors when trying to handle files larger than 2GB due to their size being too large for the filesystem. Breaking the file into smaller chunks is ...

Unique styling implementation for element situated underneath Angular 6 router-outlet

I'm currently working on implementing router transitions in my Angular application, and I've encountered an unusual problem. The styling for the router-outlet element is being applied to the element that comes after it in the DOM hierarchy. Here ...

Issue with Typescript in react: JSX element lacks construct or call signatures

After upgrading TypeScript, I encountered the error mentioned above in one of my components. In that component's render method, I have the following code: render() { const Tag = props.link ? 'a' : 'div'; return ( < ...

Improving Performance in Vue by Reducing `$set` Usage

Sharing my code snippet below <div v-for="namespace in chosenNamespaces" v-bind:key="namespace.id"> <!-- Select the Parameter --> <select @change="updateParameter($event, namespace.id)" v-model="currParameterValues[na ...

Submitting information to an HTML page for processing with a JavaScript function

I am currently working on an HTML page that includes a method operating at set intervals. window.setInterval(updateMake, 2000); function updateMake() { console.log(a); console.log(b); } The variables a and b are global variables on the HTML page. ...

angularjs: how to connect input date picker to parameters value

Having trouble with my datepicker input values not being passed as parameters in Angular and eventually to a C# parameter. Need help with setting up datepicker input and passing the values correctly. <div layout="column"> <md-content md-prim ...

How to extract HTML elements using Selenium

<html xmlns:plm="http://www.plmxml.org/Schemas/PLMXMLSchema"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>View Health Report</title> </head> <body></body> </h ...

"Looking to add some flair to your website with a

I am trying to figure out how to place a 30x30px no-repeat background image in the top left corner of a 200px by 200px div, positioned 120px from the left and 50px from the top. However, I also want to ensure that the text inside the div is displayed on to ...

Issues with the functionality of minimized AngularJS JavaScript files

I combined all JS files into one and minified them, but now none of the site features are working. There were too many separate JS files to include individually, so I decided to merge them together. Is there a better method to reduce the number of HTTP r ...

Facing difficulty in removing object in Rails with Ajax

Hey there! I’m new to Rails 4 and attempting to build a straightforward note submission and deletion app. I’ve got Ajax set up for submitting/deleting notes, but I can’t seem to get the delete function working properly. Here’s my Delete method in ...

Having trouble with installing "npm install semantic-ui-react semantic-ui-css"? Any ideas on how to fix it?

Encountered an error while trying to install Semantic UI React and Semantic UI CSS: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [ema ...

Converting form data into an object using JavaScript (Encountering an error: Cannot access property 'name' of undefined)

I recently started learning about MongoDB and I am following this tutorial here. The tutorial shows how to create a submit form that adds a person's name, age, and nationality to the database. However, I encountered the following error: TypeError: Can ...

Moving a component beyond its container using a query

After much searching, I have yet to find a solution to fix this issue. My problem involves having a list with draggable elements within a scrollable area. The goal is to drag these elements outside of the parent div into a droppable area; however, they see ...

The Infinite scroll feature fails to function once the page is loaded using ajax

Seeking assistance with implementing infinite scroll after loading a page through ajax. The current plugin functions correctly on the initial load (without ajax). However, when I load the page via ajax, the plugin stops working as expected (the content do ...

Looking to showcase a loading gif inside a popover before swapping it out with ajax-generated content

My goal is to populate a popover with content using ajax requests. Here's the setup: $('.openMessagePopover').popover({ html: true, content: function() { $threadId = $(this).data('id'); return getContent($threadId) ...

How can I efficiently include all css from node_modules in vuejs?

For my Vue.js app built with the webpack template and vuetify, I am starting by importing the vuetify css in my App.vue. <style> @import '../node_modules/vuetify/dist/vuetify.min.css' </style> I'm wondering if this is the c ...

What could be causing the last LI to drop onto a new line when floating UL to the right?

I'm currently working on creating a horizontal navigation that needs to align to the right side of the page. However, when I float the navigation to the right and then float all the list items to the left, the last item in the list breaks onto a new l ...

Submitting information to the server utilizing a POST request through jQuery

What I'm attempting to achieve: I am currently working on sending data to my server using the $.post jQuery shortcut. The issue at hand: It seems that my program is not entering my switch case, possibly due to a problem with sending the action prop ...