简体   繁体   中英

Updating second multi select dropdown based on first multi select dropdown

Help! I used this code to get 2 dropdowns working so that the second populates with the subcategories based on the selection from the first.

Populate another select dropdown from database based on dropdown selection

It works fine for single select dropdowns but I need to be able to select multiple items from the first dropdown and have it show the subcategories belonging to all of the selected items from the first.

Currently when an additional item is selected in the first dropdown, the 2nd updates to only show the subcategories for the latest selected item, presumably because it's doing the 'new Option' bit of the function. How do I get it to append the items into the 2nd dropdown when additional items are selected in the first? Many thanks.

[edit]Frustratingly I can't get it working on jsfiddle but I'll link the code hoping it still makes sense. Not sure if it's because it contains

 php?

:- http://jsfiddle.net/m1ugpb4o/5/

use jQuery Change - http://api.jquery.com/change/

and in the event handler have your ajax request to populate the second multiselect

edit: comment with the code and ill update how to do it. (use jsfiddle)

From the original code link ( Populate another select dropdown from database based on dropdown selection )

Had to change this bit:-

  function updateSubCats(){
    var catSelect = this;
    var catid = this.value;


    var subcatSelect = document.getElementById("subcatsSelect");
    subcatSelect.options.length = 0; //delete all options if any present
    for(var i = 0; i < subcats[catid].length; i++){
      subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
    }

to this:-

  function updateSubCats(){
    var catSelect = this;
    var catid = this.value;
    var testSelectionArray = new Array();

for(var j = 0; j < this.options.length; j++) {
      if (this.options[j].selected) {
           testSelectionArray.push(this.options[j].value); 
       }
}

    var subcatSelect = document.getElementById("subcatsSelect");
    subcatSelect.options.length = 0; //delete all options if any present
    var k=0;
    for(var i = 0; i < testSelectionArray.length; i++){
      catid = testSelectionArray[i];
        for(var j = 0; j < subcats[catid].length; j++){
            subcatSelect.options[k++] = new Option(subcats[catid][j].val,subcats[catid][j].id);
        }        
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM