How to Toggle the Visibility of Multiple Dropdowns Using Jquery?

I have recently started using Eric Hynds' amazing dropdown plugin and I am looking to implement the enable/disable function on multiple dropdowns. The form I am working on is quite complex, with various dropdowns that need to be toggled on and off using jQuery sliders.

If you want to check out the plugin in action, here is the link:

The code snippet provided includes a variable that I am struggling to understand as it currently only deals with one dropdown. Can anyone offer guidance on how to modify this code to work with multiple dropdowns? I am aiming to have separate buttons for triggering different dropdowns, but the current code structure does not seem to support this functionality.

var $widget = $("select").multiselect(), 
    state = true;

$("#toggle-disabled").click(function(){
   state = !state;
   $widget.multiselect(state ? 'disable' : 'enable');
});

In addition to the dropdown plugin, I am also utilizing another plugin that transforms list/input items into sliders. If things look a bit odd, it's because I am leveraging this method to capture mouse events effectively.

<li class="toggle-disabled"><label for="family">Family Medicine </label><input type="checkbox" id="family" name="family" />

Answer №1

The $widget variable serves as a jquery selector that targets ALL the <select> elements for future operations. By simply adding another <select> element, the javascript code in this example will automatically apply to both multiselects.

Take a look at this demonstration on jsfiddle:

http://jsfiddle.net/rimig/e95y2jgL/2/

I have included an additional multiselect in the example:

<select name="example-disabled" disabled="disabled" multiple="multiple" size="5">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>

<br>

<select name="example-disabled" disabled="disabled" multiple="multiple" size="5">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>

You'll notice that with just one toggle function in the javascript, it seamlessly applies to both elements.

Answer №2

How to Toggle Multi Select Dropdown List using jquery: To begin, include "bootstrap-multiselect.js" in your project.

<script src=".../js/bootstrap-multiselect.js"></script>

Next, insert the multi select dropdown list code below...

<select id="ddlCategory" class="form-control" multiple="multiple">
  <option value="1">General</option>
  <option value="2">Manufacturing</option>
</select>

<button type="button" class="btn blue btn-small" onclick="BtnDisable();">Disable</button>
<button type="button" class="btn blue btn-small" onclick="BtnEnable();">Enable</button>

Now, add the following jquery code...

<script>
     $(function () {

        $("#ddlCategory").multiselect({
          nonSelectedText: '--Category--',
          disableIfEmpty: true,
          includeSelectAllOption: true,
          allSelectedText: 'No option left ...',
          numberDisplayed: 1,
          maxHeight: 400
        });

     });
     
    function BtnDisable(){
      $("#ddlCategory").multiselect('disable');
    }
    
    function BtnEnable(){
      $("#ddlCategory").multiselect('enable');
    }

</script>

Lastly, here are some screenshots of the expected output...

https://i.sstatic.net/2JpAZ.png

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

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

https://i.sstatic.net/9QedT.png

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

Tips for updating datatables following an ajax request

I've attempted various methods to refresh my data table following an AJAX Call but have had no success. I have tried using the draw() and ajax.reload() functions, but nothing seems to be working. Do you have any suggestions on how I can successfully r ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

Automatically updating markers on Google Maps v3

I'm utilizing the capabilities of Google Maps V3 to showcase various pins. My goal is to update these markers periodically without interfering with the current location or zoom level on the map. I aim for the markers to refresh every x seconds. How c ...

Is there a tutorial for JavaScript with Selenium WebDriver?

I've recently embarked on the journey of writing tests with Selenium WebDriver and JavaScript. However, I'm facing a roadblock in finding a comprehensive tutorial that covers element locators, commands, verification commands for elements, clickin ...

Activation of the button is required once the Recaptcha and checkbox have been successfully validated

Just diving into the world of Django and jQuery, so reaching out for some guidance (pretty much a beginner here). I'm looking to activate the Start Test button only after the recaptcha validation is confirmed on the server side and the checkbox has be ...

Calculate and Organize the Common Elements in an Array

Here is an example schema structure: module.exports = function(connection, mongoose) { // var autoIncrement = require('mongoose-auto-increment'); var UsersSchema = new mongoose.Schema({ first_name: String, last_name: String, ...

Filter an array of objects in Javascript based on a key present in another array of objects

Having two arrays, one with all products and one with products a user can access, both sharing a common ID. The goal is to filter the products array to only include those accessible to the user. All available products (products) [{ "productName": "My P ...

jQuery loads browser cache to override transitions in the body class

My .load ajax function: 1) Click link 2) The requested page loads with a smooth css transition animation (applying/removing body classes) 3) If the page loads faster than 400ms, it should wait before revealing the page by removing the body class While ...

Building Firestore subcollections with the latest WebSDK 9: A step-by-step guide

I'm looking to create a subcollection within my document using the webSDK 9, specifically the tree-shakable SDK. While I have come across some solutions, they all seem to be outdated and reliant on the old sdk. Just for context, I am working with Ne ...

Leverage the NextRouter functionality without the need for a React component

I've created a custom hook that checks if a user is logged in and redirects them to the login page if not. Below is a simplified version of the hook assuming the user is not logged in: import { useRouter } from 'next/router'; export default ...

The JavaScript function will only run after the user clicks the button twice

I attempted to create a button that toggles the visibility of a div element. Initially, I added the "onclick" event to the button and wrote this function: function showElement() { var element = document.querySelector('.blocks-fnd-div'); if ...

Need help creating perfect round buttons with bootstrap 4?

After incorporating this fiddle into my code, the goal was to design a circular button. View Fiddle Here The code provided is for bootstrap 3. However, when using it with bootstrap 4, the button ends up being square instead of circular. See example here: ...

Ways to acquire dynamic content without relying on Remark/Grey Matter

In my stack of technologies, I am using nextJS with react and typescript. While I have successfully set dynamic routes for my blog posts, I am now facing a challenge in creating pages that do not rely on markdown. Despite searching extensively for code exa ...

What is the process of embedding a string with pug code into a pug file?

How can I interpolate a string with pug formatted code in a pug file? Here is what I have tried: - var text = "i.home.icon" div= text div !{text} div #{text} div ${${text}} div {{text}} div {text} div \#{text} div \{text} div ${text} div # ...

Issues encountered when using PrimeNG tree select component with filter functionality

After successfully implementing the new primeng treeselect component with selection mode as "checkbox," I encountered an issue when trying to add a [filter]="true" as shown in the PrimeNG demo. <p-treeSelect [(ngModel)]="selectedNode1" [options]="nodes1 ...

Positioning of Ajax modal popups on smaller screens

In my Asp.net/C# web application, I have a modal popup that contains multiple placeholders. However, I am facing an issue when trying to access the modal popup on smaller screens like iPads or iPhones. The page only displays half of the modal popup, maki ...

Get access to the file upload field using ajax

I'm encountering an issue with accessing the file upload field //HTML <input type='file' name='images' id="images" multiple> ////////////////// $('.bt-add-com').click(function(){ var formdata = new For ...

React component's state is not being correctly refreshed on key events

Currently facing an issue that's puzzling me. While creating a Wordle replica, I've noticed that the state updates correctly on some occasions but not on others. I'm struggling to pinpoint the exact reason behind this discrepancy. Included ...

Ways to limit the display of search result page numbers at the bottom of the search results page using PHP

I'm experiencing an issue with limiting the number of search result pages in my PHP page. Currently, I have 3 fields for user input and the search results are displayed at the bottom. When all fields are selected, the page numbers keep increasing at ...

What are some top-notch Responsive Lightbox or Modalbox options similar to those found on Facebook or Instagram?

Is there a recommended jQuery plugin that can help me create a gallery with images, comments, and descriptions similar to the layouts on Facebook and Instagram? ...