Troubleshooting Limitation Problem with Bootstrap Multiselect

I recently created a multiselect dropdown menu using Bootstrap Multiselect. I successfully set a limit on the number of options that can be selected (in this case, 5), and once the limit is reached, the additional options become disabled. Everything works perfectly, except when attempting to select more than 5 options using the SHIFT key. In this scenario, my jQuery code to prevent further selection does not work, allowing me to exceed the limit. Any suggestions or solutions would be greatly appreciated.

JSFIDDLE

 jQuery('#soft_skill_list').multiselect({
        enableFiltering: true,
        maxHeight:400,
        enableCaseInsensitiveFiltering:true, 
        nonSelectedText: 'Soft Skills *', 
        numberDisplayed: 2, 
        selectAll: false, 
        onChange: function(option, checked) {
                // Get selected options.
                var selectedOptions = jQuery('#soft_skill_list option:selected');
 
                if (selectedOptions.length >= 5) {
                    // Disable all other checkboxes.
                    var nonSelectedOptions = jQuery('#soft_skill_list option').filter(function() {
                        return !jQuery(this).is(':selected');
                    });
 
                    nonSelectedOptions.each(function() {
                        var input = jQuery('input[value="' + jQuery(this).val() + '"]');
                        input.prop('disabled', true);
                        input.parent('li').addClass('disabled');
                    });
                }
                else {
                    // Enable all checkboxes.
                    jQuery('#soft_skill_list option').each(function() {
                        var input = jQuery('input[value="' + jQuery(this).val() + '"]');
                        input.prop('disabled', false);
                        input.parent('li').addClass('disabled');
                    });
                }
            }});
   
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />

<select name="soft_skill_list[]" class="soft_skill_list"  id="soft_skill_list" multiple="multiple">
  <option>Analysing data</option>
  <option>Banquets Operations</option>
  <option>Concierge Operations</option>
  <option>Customer service experience</option>
  <option>Measuring and calculating</option>
  <option>Micros</option>
  <option>Numeracy Skills </option>
  <option>Opening Hotels</option>
  <option>Opera</option>
  <option>Outside catering</option>
  <option>Pre-opening</option>
  <option>Procedures </option>
  <option>Proficiency in computer programming</option>
  <option>Public speaking experience </option>
  <option>Reservation</option>
  <option>Restaurants operations</option>
  <option>Revenue Analysis</option>
  <option>Rooms Division</option>
  <option>Safety and Security</option>
  <option>Sales administration</option>
  <option>Sales Operations</option>
  <option>Social Media</option>
</select>

Please refer to the image here https://i.stack.imgur.com/5l5iX.png

Answer №1

To prevent the Shift key from being used when clicking on a list option, you can use the following jQuery code:

For reference, please visit -> JSFIDDLE

var shiftClick = jQuery.Event("click");
shiftClick.shiftKey = true;

    $(".multiselect-container li *").click(function(event) {
        if (event.shiftKey) {
           //alert("Shift key is pressed");
            event.preventDefault();
            return false;
        }
        else {
            //alert('No shift hey');
        }
    });

Answer №2

It is important to validate each selection individually if there are more than 5 options chosen.

if (selectedOptions.length >= 5) {
  if (selectedOptions.length > 5) {
    // Display error message
  } else {
    // Continue with current process
  }

When checkboxes are selected one by one, the total number of selections can never exceed 5.

Answer №3

In order to prevent the disabling of checkboxes in other multiselect controls on the same page that have the same option value, it is important to ensure that the correct selector function is used when enabling/disabling the checkboxes. This can be achieved by replacing the following line of code:

var input = jQuery('input[value="' + jQuery(this).val() + '"]');

with this:

var input = jQuery('#soft_skill_list + .btn-group input[value="' + jQuery(this).val() + '"]');

Failure to make this change may result in unintended consequences and affect checkboxes in multiple multiselect controls.

The updated implementation should look like this:

jQuery('#soft_skill_list').multiselect({
    enableFiltering: true,
    maxHeight:400,
    enableCaseInsensitiveFiltering:true, 
    nonSelectedText: 'Soft Skills *', 
    numberDisplayed: 2, 
    selectAll: false, 
    onChange: function(option, checked) {
            // Retrieve selected options.
            var selectedOptions = jQuery('#soft_skill_list option:selected');

            if (selectedOptions.length >= 5) {
                // Disable all remaining checkboxes.
                var nonSelectedOptions = jQuery('#soft_skill_list option').filter(function() {
                    return !jQuery(this).is(':selected');
                });

                nonSelectedOptions.each(function() {
                    var input = jQuery('#soft_skill_list + .btn-group input[value="' + jQuery(this).val() + '"]');
                    input.prop('disabled', true);
                    input.parent('li').addClass('disabled');
                });
            }
            else {
                // Enable all checkboxes.
                jQuery('#soft_skill_list option').each(function() {
                    var input = jQuery('#soft_skill_list + .btn-group  input[value="' + jQuery(this).val() + '"]');
                    input.prop('disabled', false);
                    input.parent('li').addClass('disabled');
                });
            }
        }});

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

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...

The event SelectedIndexChanged is not triggering as expected on dropdown lists that are created dynamically

My Telerik RadComboBox triggers Javascript on change to fetch data from the database via AJAX and populate a second dropdown list. I need to fill text boxes based on the selection of the second dropdownlist. The code for the two dropdownlists is as follows ...

The scroll event listener activates based on the distance I have scrolled

const processChatRead = useCallback(() => { const chatWindow = refEntries.current; if ( chatWindow.scrollTop > chatWindow.scrollHeight - 800 && activeRoom && conversations?.content?.length > 0 && ...

Utilizing 'this' in jQuery: Image swapping with thumbnails, Twitter Bootstrap framework

Is it possible for jQuery's 'this' to simplify my code? You can view the full code here. Thank you for any help or suggestions. Here is the jQuery code: /* Ref: http://api.jquery.com/hover/ Calling $( selector ).hover( handlerIn, handler ...

What is the best way to connect a Jquery plugin to a table within a partial view following an ajax request?

I have a main view that utilizes a partial view to display items in a table format. Main View (Enclosed within a div, it references the Partial View) <div id="divList"> @Html.Action("_list") </div> Partial View (Displaying a list of it ...

Unable to reference a property or method in Vue.js and Vuetify due to an issue with the <v-btn-toggle> button causing an error

Just started using vuetify and exploring the <v-btn-toggle> component for the first time. I'm trying to implement a toggle feature to filter my user list based on employee, manager, or admin types... Check out a snippet of my code below: <v ...

'this' while being utilized in a nested function

const EventEmitter = require('events').EventEmitter; const Counter = function (init) { this.increment = function () { init++; this.emit('incremented', init); } } ...

To make changes to an item, simply tap on the Catalog number

I'm currently facing a challenge in trying to implement a modal window that displays detailed information about a selected item based on the catalog number. The catalog number serves as the trigger to open the modal. Since I'm relatively new to a ...

Discovering the specific element that was clicked from a collection of elements

I'm dealing with a scenario where multiple divs share the same class. There is a dropdown that alters the background color of one of these divs when a certain option is selected (for example, option 2 changes div #2's background color). My dile ...

What is the reason behind getComputedStyle having visibility set to visible?

What is the reason behind getComputedStyle always returning element visibility as visible even when no explicit visibility has been set? For instance: getComputedStyle($('#block1')[0],null).visibility; --- "visible" Meanwhile: $('#block1&a ...

Responsive div not displaying background image

Here is a straightforward and easy-to-understand code snippet: HTML markup: <div class="jumbotron text-center top-jumbotron"> </div> CSS: .top-jumbotron { background: #ffcc00; background-image: url('../../bootstrap/img/home-pag ...

Display error messages in Vue.js

Within this component, I have a method that updates an employee. My goal is to display the error message in the view immediately after the "errorMessage" variable is assigned/changed within the "error" callback of the ajax call. var EmployeeEdit = Vue ...

What strategies can be used to stop elements from reverting to their original state?

Hey there, I'm currently experimenting with animation and trying to create a cool two-step effect: 1. elements falling down and 2. pulsating on click. However, I've run into an issue where after the clicking action, the elements return to their o ...

Rearrange the position of one div to be placed next to another div and assign the float property

I have numerous divs located on my webpage, including .rightColumnBar and .divAttributes. HTML <div class="mainContent"> <div class="pageContent"> <form id="createLead" class="frmDiv clear" action="/leads/create_lead.html?lead_id=3287" nam ...

What is the best way to ensure a PrimeVue TabPanel takes up the full vertical space and allows the content within the tabs to be scroll

I have created a sandbox demo to illustrate my issue. My goal is to make the content of tabs scroll when necessary but fill to the bottom if not needed. I believe using flex columns could be the solution, however, my attempts so far have been unsuccessful. ...

Is it possible to create a grid by arranging each statement with a specific format?

After fetching and parsing some data, I have utilized the 'each' function to display it: $.ajax({ url : 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent('htt ...

Ensure to use e.preventDefault() method when handling form submissions

Check out this code snippet: <form> <input type="text" name="keyword" value="keyword"> <input type="submit" value="Search"> </form> I'm seeking assistance with implementing jQuery to prevent the default action of the submit b ...

Display and conceal different sections using hyperlinks

Hey there, I'm back with another issue related to this code snippet on jsfiddle: https://jsfiddle.net/4qq6xnfr/9/. The problem I'm facing is that when I click on one of the 5 links in the first column, a second div appears with 3 links. Upon clic ...

To continue receiving rxjs updates, kindly subscribe if the specified condition is met

Is there a way to check a condition before subscribing within the operator chain? Here's what I have: // parentElem:boolean = false; // the parent elem show/hide; let parentElem = false; // inside the ngAfterViewInit(); this.myForm.get('grandPa ...

Resolving redundancy in Typescript Material-UI Table codebases

Apologies for the ambiguous question title, it was difficult to come up with something more specific. I am currently exploring the Typescript implementation of Material-UI tables, specifically focusing on the table section titled "Sorting and selecting". ...