"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:

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

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

Efficiently Minimize Bootstrap Components Upon Clicking the Link

I've successfully created a navigation menu that expands and collapses without using a dropdown feature. However, I'm encountering an issue where I can't seem to toggle the div when clicking on a menu link. I attempted to use JavaScript to c ...

In JavaScript, JSON data is parsed using a comma separator

Here is the format of my data: [{"QualID":1,"Qualification":"Van Driver"},{"QualID":3,"Qualification":"Safety Cert"},{"QualID":4,"Qualification":"Welder"}] I am look ...

Executing an AngularJS function through CasperJS is a common task that can

I am facing a challenge with testing a directive within a controller. The unit tests I am trying to write involve executing this code, which is triggered not by a click event but rather by a socket.io emit. Instead of attempting to mock socket.io, I am exp ...

Eliminating the impact of a CSS selector

I have a complex mark-up structure with multiple CSS classes associated: classA, classB, classC, classD. These classes are used for both styling via CSS and event binding using jQuery selectors. The Challenge: I need the jQuery events to be functional whi ...

Troubleshooting problems with AngularJS loading data through ajax

One of the custom widgets in my application relies on Angular functionality. On a particular page, this widget is loaded via ajax. The following content is fetched through ajax and inserted into the DOM: _abc.html: <script type="text/javascript">c ...

Dispatching $emit / $broadcast events from multiple areas of the code and capturing them in a single location

I have a practice of sending $emits (or $broadcasts) from various parts of the code and different controllers, but intercepting them all from one centralized place. While this approach seems to be functioning properly, I am unsure if it may be considered b ...

Understanding the use of "el" in a function parameter in Vue Js

I am new to VueJS, so please be patient with me. I am trying to code a function that will scroll to an element with a specific ID when a "?" is used in the URL. I want it to have the same effect as demonstrated here. My assignment requires me to follow a ...

The browser's window.location.href fails to redirect the page

Here are my functions: <a onClick="check_claims(this)" type="button" href="javascript:void(0)" redirurl="www.facebook.com" >Invite</a> function check_claims(ele){ var select_claims = document.getE ...

Leveraging the power of AWS API Gateway and Lambda for seamless image upload and download operations with Amazon

I have successfully created a lambda function to handle image uploads and downloads to s3. However, I am encountering difficulties with the proxy integration from the API Gateway. Despite reviewing the documentation and looking at this specific question ...

Why are the UI components (`Card Number`, `MM/YY`, `CVC`) not being displayed in the React app when using Card

Having an issue where the CardElement Ui component is not visible in the image provided. It should appear above the Order Total: $0 next to the payment method. I've attempted various debugging methods without success. I'm still working on resolv ...

When the function is clicked, an error occurs that says: "return is a reserved word"

I am attempting to trigger a popup window when clicking on the link button, but I keep getting an error stating that "return" is a keyword and expecting an identifier. I'm using ASP.NET for this functionality. <asp:LinkButton ID="CommentAction" h ...

How to bypass CORS restrictions in XMLHttpRequest by manipulating HTTP headers?

Currently experimenting with the (deprecated) Twitter API 1.0 For instance, I am interested in retrieving data from the API utilizing AJAX browser requests on cross-origin web pages. This could be a new tab, a local HTML file, or any established website. ...

Needing to utilize the provide() function individually for every service in RC4

In Beta, my bootstrapping code was running smoothly as shown below: bootstrap(App, [ provide(Http, { useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, helperService: HelperService, authProvider: AuthProvider) => new CustomHt ...

Navigating URLs with Ajax Requests in CakePHP

How can ajax calls in javascript files located in the webroot be handled without PHP interpretation? In my project using CakePHP and require.js, I avoid placing javascript directly in views. To address this issue, I set a variable in the layout to store t ...

Error: Unable to call dispatch method on this.$store object

I'm diving into Vue and hitting a wall with this error message. TypeError: this.$store.dipatch is not a function I've set up the store.js file and am attempting to call actions from within a vue file. I've scoured the internet for answers ...

How to create a loop in Selenium IDE for selecting specific values from a drop-down list?

Is there a way to use Selenium IDE and JavaScript to test a drop-down box with specific items, not all of them, and continuously loop through until the entire list is covered? Any tips or recommendations on how to accomplish this? ...

What is the best way to implement an event listener for every button in a table row outcome?

I have a Rails application where I am populating a table using an @results variable, with each row representing a @result. My goal is to have buttons associated with each @result, and I'm attempting to use a JavaScript event listener for each button a ...

Navigating from the Login Page to the Dashboard in Vue.js following successful token validation

I am facing an issue with the code that is supposed to redirect the User to the dashboard page if they have a token. Despite generating a JWT token from my Spring Boot backend and sending it to Vue for processing, the redirection is not working as expect ...

Horizontal scrolling alone is proving to be ineffective

My current HTML code includes a table that is integrated with PHP Laravel. The data is being pulled from Admin.php to populate the table, resulting in it being wider than the screen window. To address this, I added a horizontal scroll bar for navigation pu ...

Steps to resolve the Angular observable error

I am trying to remove the currently logged-in user using a filter method, but I encountered an error: Type 'Subscription' is missing the following properties from type 'Observable[]>': _isScalar, source, operator, lift, and 6 more. ...