Search code examples
javascriptjquerymulti-selectbootstrap-multiselect

Boostrap Multiselect condition if checked


I have one array with values, and i make a request this send informations to multiselect.

When i open my select, i have a couple values pre-selected.

My problem is, if i click to unchecked a checkbox on the boostrap multiselect, i wanna remove this information from my array. If i click in the checkbox i wanna put the value back in the array.

In my code i first check if the value is in the array, but the interaction with the boostrap select isn't what i want to do.

    // that bring the information in boostrap multiselect
    var vetornovo = ValueChecked();

    // here i try to detect the change to check and unchecked but doesnt works
    // all informations is selected: "selected" by default
    $("#os-select-list").change(function() {
                // i take the checkbox value.
                var valueck = parseInt($("#os-select-list option:selected").text());

                // if the information is in that i array when i click to unchecked then remove.
                  if (vetornovo.indexOf(valueck) > -1) {
                        index = $.inArray(valueck, vetornovo);
                        vetornovo.splice(index, 1);  
                        console.log(vetornovo);     
                    // when i click to selecte the value again i push and insert back to the array.
                  } else {
                    vetornovo.push(valueck);
                    console.log(vetornovo);   
                  }
    });

i wanna understand what is wrong, why when i click on the checkbox doensn't do and some times duplicated the content.


Solution

  • Presuming you are using https://www.jqueryscript.net/form/jQuery-Multiple-Select-Plugin-For-Bootstrap-Bootstrap-Multiselect.html

    the command to detect change is

    * Triggered on change of the multiselect.
    *
    * Not triggered when selecting/deselecting options manually.
    *
    * @param {jQuery} option
    * @param {Boolean} checked 
    */
    onChange : function(option, checked) {
    
    }
    

    not 'change' as you have in your code

    There are many 'selects' that work with bootstrap - I like https://developer.snapappointments.com/bootstrap-select/ - it has good examples and easy to read instructions - worth a look if you are just starting out...