"Dynamic value changes in bootstrap multiselect dropdowns triggered by selection in another multiselect dropdown

I am trying to enhance the functionality of my multiselect dropdown in Bootstrap by updating the values based on another multiselect selection. Currently, the code works well with one selection, but as soon as I include the class="selectpicker", it stops functioning and I lose my options.

Here is the code snippet I am currently using:

HTML:

<select id="deptos" class="selectpicker"></select>
<select id="munis" class="selectpicker"></select>

Javascript: The initial script was referred from here

<script>    
window.onload = function() {
        var depto = JSON.parse("{{deptos|escapejs}}"),//deptos comes from a django view.
            depto_select = document.querySelector('#deptos'),
            muni_select = document.querySelector('#munis');

        setOptions(depto_select, Object.keys(depto));
        setOptions(muni_select, depto[depto_select.value]);
        
        depto_select.addEventListener('change', function() {
            setOptions(muni_select, depto[depto_select.value]);
        });
            
        function setOptions(dropDown, options) {
            dropDown.innerHTML = '';
            options.forEach(function(value) {
            dropDown.innerHTML += '<option value="' + value + '">' + value + '</option>';
            });
        }  
    };

    $('select').selectpicker();
</script>

This is how it performs with basic selections:

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

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

However, when I introduce the class="selectpicker", it displays like this:

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

Answer №1

To update the options, include

$('.selectpicker').selectpicker('refresh')
in the setOptions() function:

window.onload = function() {
  // provs is an object but can be seen as a lookup table
  var provs = {
        'British Columbia': ['Victoria', 'Sanitch'],
        'Ontario': ['Bracebridge', 'Waterloo']
      },
      // store references to the two drop-downs
      prov_select = document.querySelector('#prov'),
      town_select = document.querySelector('#town');

  // fill the provinces drop-down
  setOptions(prov_select, Object.keys(provs));
  // populate the town drop-down
  setOptions(town_select, provs[prov_select.value]);
  
  // add a change event listener to the provinces drop-down
  prov_select.addEventListener('change', function() {
    // retrieve the towns in the selected province
    setOptions(town_select, provs[prov_select.value]);
  });
    
  function setOptions(dropDown, options) {
    // clear any existing values
    dropDown.innerHTML = '';
    // insert the new options into the drop-down
    options.forEach(function(value){
      dropDown.innerHTML += '<option>' + value + '</option>';
    });
    $('.selectpicker').selectpicker('refresh') // This line was added from previous version
  }  
};
<html>

<!-- I imported it since I didn't download it XD -->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css" rel="stylesheet" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<select id="prov" class="selectpicker"></select>
<select id="town" class="selectpicker"></select> <!--You can add multiple after class="" for multiple selection-->

</html>

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

Encountering a 400 error while trying to implement file upload feature in Spring AngularJS -

Whenever I attempt to upload a file using Spring and AngularJS, I keep encountering the dreaded 400 Bad Request error: > error: "Bad Request" > exception: "org.springframework.web.multipart.support.MissingServletRequestPartException" > message: " ...

Prevent keypress from being detected while the confirm box is displayed

My website heavily relies on key events, and for certain actions, it triggers a bootbox confirm box. This confirm box appears over a transparent layer, blocking all mouse click actions unless the user interacts with the confirm box. Now, I also want to dis ...

Having difficulty displaying Laravel API data with Relationship in Vue Js

Working on a project that involves Laravel 10 API and Vue.js 3 frontend In my EmployeeController.php file, I have three models: Employee, Title, and Salary. The Employee model has a many-to-many relationship with the Salary and Title models, while the Sal ...

Including a label for an array within an unnamed array in a JSON string

Is there a way to transform the following data: [{"name": "Donald"}, {"name": "George"}] Into this format instead: {MyArray: [{"name": "Donald"}, {"name": "George"}]} I am currently working on a database server that I built using node.js, express, an ...

Unable to load JSON model texture

I successfully transformed an obj file into a json model using a Python tool, and now I am attempting to load it into my project. Below is the code snippet: var camera, scene, renderer; var mesh, aircraft; function addModelToScene( geometry, materials ) ...

Animating the height of a div using jQuery after loading dynamic content

When I load a page using AJAX, the content is represented as a string. I am then trying to animate the height of a container if the content is larger than the current height of the container. However, for some reason, the variable _height always ends up ...

The process of filtering arrays and utilizing the V-for directive in Vue.js

Utilizing Vue.js, I am attempting to iterate through an array of levels. I successfully received the response json in actions with a forEach function like: let filters = [] const array = response.data array.forEach((element) => ...

Encountering issues with Yarn Install during production build. Issue states: "Error - [email protected] : The engine "node" does not align with this module"

Currently facing an issue while deploying a ReactJS Project on the PROD environment. The previous command "Yarn install" was working fine, but now it's failing with an error message. The error that I'm encountering is: info [email protected ...

Showing a div with 2 unique data attributes - such as displaying Currency and Quantity

My E-Commerce website is created using HTML, JavaScript, and PHP. On the product details page, users can add products to their cart, so I show the total cart value. I need the total amount displayed in a decimal number format (10,2). Currently, when a u ...

The error message thrown by React JS webpack is "Module not found: Error: Unable to resolve 'src/content/Login/LoginAuthentication'"

Currently working with web "webpack" version "^5.74.0" for my React js project. During the npm start command, webpack is throwing the following error: ERROR in ./src/layouts/SidebarLayout/Sidebar/SidebarMenu/items.ts 21:0-83 Module not ...

When you press multiple buttons, the correct button will reveal an image while the incorrect buttons will display an X

Could you lend a hand with the code below? Your assistance is truly appreciated :). Thank you in advance. I need help setting up a functionality where clicking on the correct button (e.g. H) will display a checkmark and a forward link image. If the user c ...

Is it possible for me to include additional fields in a vuetify calendar event?

Is there a method to incorporate additional fields, such as a description, in addition to the name and start/end time for an event on the v-calendar's day view? ...

"Troubleshooting: Difficulty with hover function in jqgrid not functioning on colored rows

My JQGrid setup includes the following: <table id="grid"></table> var data = [[48803, "DSK1", "", "02200220", "OPEN"], [48769, "APPR", "", "77733337", "ENTERED"]]; $("#grid").jqGrid({ datatype: "local", height: 250, colNa ...

How can you access and utilize the inline use of window.location.pathname within a ternary operator in

I need assistance with writing a conditional statement within Angularjs. Specifically, I want to update the page to have aria-current="page" when a tab is clicked. My approach involves checking if the tab's anchor href matches the current window' ...

Guide on efficiently inserting values into an array of objects

I'm looking to extract specific values from the enum below enum p { XDR = 1, PT1M = 2, PT1M_ = 2, PT5M = 3, PT5M_ = 3, PT15M = 4, PT15M_ = 4, PT1H = 5, PT1H_ = 5, P1D = 6, P1D_ = 6, P7D = 7, P1W = 7, ...

Converting an HTMLElement to a Node in Typescript

Is there a method to transform an HTMLElement into a Node element? As indicated in this response (), an Element is one specific type of node... However, I am unable to locate a process for conversion. I specifically require a Node element in order to inp ...

Combining two interconnected documents in Mongoose: merging references

Currently, I am in the process of learning how to work with NoSQL after having a background in relational databases. For this specific project, I am utilizing Express along with Mongoose. The main challenge I am facing involves callbacks when attempting t ...

Implementing AngularJS JQuery Datatables Directive for Displaying Multiple Data Tables within a Single View

I have successfully implemented the following directive: angular.module('myApp').directive('jqdatatable', function () { return { restrict: 'A', link: function (scope, element, attrs, ngModelCtrl) { ...

Exploring the process of setting up a datasource for Select2 in October CMS using the integrated Ajax Framework

Looking to utilize the extensive AJAX framework provided by October CMS to populate a Select2 box with data. The process of using a remote dataset in Select2 involves the following steps: $(".js-data-example-ajax").select2({ ajax: { url: "https://a ...

Struggling to comprehend the node.js walker concept

I am struggling to grasp the concept of how the signature/header of the node.js walker functions. I understand that a walker can go through a directory and apply filters, but I'm unsure about how the signature of the .on function works. For example: ...