How to: programatically fill <sp-dropdown>

Hi,

How can I fill a <sp-dropdown> lista with separator and disabled element programmatically from pure javascript?

Thx
Karoly

There are many ways to accomplish this – it really depends on if you’re using any frameworks or not.

From a pure vanilla JS way, you could do it this way:

const items = ["Chicago", "New York", "-", "Amsterdam", "London"];
const disabledItems = ["New York"];

const dropdown = document.createElement("sp-dropdown");

const menu = document.createElement("sp-menu");
menu.setAttribute("slot", "options");

const menuItems = items.map((item, idx) => {
    if (item === "-") return document.createElement("sp-menu-divider");
    const menuItem = document.createElement("sp-menu-item");
    menuItem.textContent = item;
    if (idx === 0) menuItem.setAttribute("selected");
    if (disabledItems.indexOf(item) > -1) menuItem.setAttribute("disabled");
    return menuItem;
});

menuItems.forEach(item => menu.appendChild(item));
dropdown.appendChild(menu);
document.querySelector("#attach").appendChild(dropdown);

This results in the following visual appearance:

image

1 Like

Note – this is the HTML DOM the above creates:

<sp-dropdown>
 <sp-menu slot="options">
  <sp-menu-item selected>Chicago</sp-menu-item>
  <sp-menu-item disabled>New York</sp-menu-item>
  <sp-menu-divider></sp-menu-divider>
  <sp-menu-item>Amsterdam</sp-menu-item>
  <sp-menu-item>London</sp-menu-item>
 </sp-menu>
</sp-dropdown>
1 Like

Thank you Kerri!
It’s a pleasure work with you.

/Karoly

Hi @kerrishotts ,

Could you give me an example how can I:
- Remove they all menuitems?
How can I get “menuItems” array from “menu”?
How can I empty “menuItems”
- Get the selected menuitem
- How can I change programmatically the selected item

Could you give me a link for detailed javascript class API description?
In the official Spectrum API description I can see only HTML definitions.

Thx
Karoly

@kaci65 , what you’re asking, is a basic JS DOM manipulation and not really something specific to UXP

1 Like

Thank you @Karmalakas !

/Karoly

Another way to do it is to just use innerHTML. It’s not better than any other method. It’s just another way. It’s pretty simple.

To clear the existing dropdown items…

document.getElementById("yourSpMenuID").innerHTML='';

To fill menu items…

document.getElementById("yourSpMenuID").innerHTML='Your HTML Code Here';

For mine, I first create an array of file names for user saved presets. I then run a loop to create a text string and use innerHTML to update the dropdown list with the text string

//presetsList is an array with the names of the presets
//presetSelection in the sp-menu ID
let dropdownText='';

for(let i=0; i<presetsList.length; i++){ 

dropdownText=dropdownText+'<sp-menu-item value="'+presetsList[i]+'">'+presetsList[i]+'</sp-menu-item>';

}

document.getElementById("presetSelection").innerHTML=dropdownText;

1 Like