-1

I am trying to figure out how to add the name for my dropdown value, which by default is empty. I would like to call it 'Show all' instead. It works with map filters, so it displays the values by function.

picture

function buildDropDownList(title, listItems) {

    const filtersDiv = document.getElementById("filters");
    const mainDiv = document.createElement("div2");
    const filterTitle = document.createElement("h3");
    filterTitle.innerText = title;
    filterTitle.classList.add("py12", "txt-bold");
    mainDiv.appendChild(filterTitle);

    const selectContainer = document.createElement("div2");
  
    selectContainer.classList.add("select-container", "center");

    const dropDown = document.createElement("select");
    dropDown.classList.add("select", "filter-option");

    const selectArrow = document.createElement("div2");
    selectArrow.classList.add("select-arrow");

    const firstOption = document.createElement("option");

    dropDown.appendChild(firstOption);
    selectContainer.appendChild(dropDown);
    selectContainer.appendChild(selectArrow);
    mainDiv.appendChild(selectContainer);

    for (let i = 0; i < listItems.length; i++) {
        const opt = listItems[i];
        const el1 = document.createElement("option");
        el1.textContent = opt;
        el1.value = opt;
        dropDown.appendChild(el1);
    
    filtersDiv.appendChild(mainDiv);
}
Martin Brisiak
  • 3,872
  • 12
  • 37
  • 51
  • Does this answer your question? [How can I set the default value for an HTML – Celso Wellington Oct 29 '20 at 21:51

1 Answers1

0

That item is an option without a value. The best solution would be to avoid getting empty elements, but if that's not possible, you can do a small tweak, like:

for (let i = 0; i < listItems.length; i++) {
    const opt = listItems[i];
    const el1 = document.createElement("option");
    el1.textContent = (opt && opt.trim()) ? opt : "Show all";
    el1.value = opt;
    dropDown.appendChild(el1);
}

And also, make sure that you properly close the curly brackets of your loop.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
  • Hi, I tried it, unfortunately didn't work. opt refers to the values I stated in filters , if changed, all data disappears. – Viktoria O Oct 30 '20 at 02:34
  • @ViktoriaO can you create a JSFiddle or a snippet about your problem? That way I could test my fix and edit my answer with some improvements – Lajos Arpad Oct 30 '20 at 04:59
  • Thank you! I just figured it out! Blank space was added by 'dropDown.appendChild(firstOption);'. I needed to add ' $(firstOption).text('Show all');' – Viktoria O Oct 30 '20 at 10:39