Search code examples
jquerysharepoint-2013

SharePoint cascading dropdown to multi-select field, retaining selections when filter changes


I followed the cascading dropdown with jquery that is listed here: https://www.c-sharpcorner.com/blogs/cascading-dropdownlist-in-sharepoint and it works fine. The child entry is a multi-select field. When you change the parent field, it resets the child list to the applicable children.

Parent: Manufacturer that has Brand in Title
Child: list of products for each brand. Product is listed as Title with a field for BrandLookUp.
UPDATE: Some Child feeds are listed multiple times because they are associated with multiple years. Even though the ID for each child is different, I just need to retain the child title field (item) for this part of the list. I.e.
-ID - Brand - Item - Year
-1 - XYZ - A - 21
-2 - XYZ - A - 22
-3 - ABC - B
-4 - WXY - C

I am trying to figure out how to modify the code to only display unique item names when the child list is populated.

UPDATE 2: I realized while there is a code solution, I could also fix it by restructuring the data. I changed the year field to a multi-value and added the multiple years, then removed the duplicate entries. The filter fields works and pulls the item for the correct year.


Solution

  • Checked the linked code. I do not have the environment to test, but here is my suggestion.

    • Only append new products to the child. Never call $(child).empty();. Add option to the child selector to select the options in it and call $(childOptions).hide(); to hide them all.

         var childOptions = $("................. option");
         childOptions.hide();
      
    • When brand is changed, first check if its products are already in the list. Better, keep an array of brands products of which are already added to the child, visible or not. If they are on the list, do not add them again. When you are going to add new products to the select, add a data-brand attribute to the options so you can filter them later.

        for (index in data.d.results) {  
            options += "<option value='" + data.d.results[index].Id + "' data-brand='" + brandName + "'>" +  
                data.d.results[index][params.childLookupField] + "</option>";  
        }  
        $(child).append(options);
      
    • Select the product options of the current brand and show them, something like $("option[data-brand='ACME']").show();