How to set selected value for multiple dropdown

Viewed 73

I'm populating multiple dropdowns with the same data.

How do I set the selected value from the array below for each iteration?

const arraylist = ['Tom', 'Joe', 'Bill'];
const iterable = ['Mark', 'Jill', 'Ben', 'John', 'Tom', 'Joe'];

let dropdown = '';
for (let i = 0; i < 5; i++) {
    dropdown += "<select name='samedata' class='dropdownlist'>";
    for (const [index, v] of Object.entries(iterable)) {
        let checked = arraylist.includes(v) ? 'selected' : '';
        dropdown += `<option value="${v}" ${checked}>${v}</option>`;
    }
    dropdown += '</select>';
}

Where the first dropdown having Tom selected, second having Joe and the rest having nothing selected.

1 Answers

I had to add in some additional code to get it to work. First to check to see if a 'selected' option had been found for each <select> iteration and then an array.splice() to remove that option from the arraylist array.

const arraylist = ['Tom', 'Joe', 'Bill'];
const iterable = ['Mark', 'Jill', 'Ben', 'John', 'Tom', 'Joe'];

let dropdown = '';
for (let i = 0; i < 5; i++) {
  let found = false;
  dropdown += "<select name='samedata' class='dropdownlist'><option></option>";
  for (const [index, v] of Object.entries(iterable)) {
    let checked = !found && arraylist.includes(v) ? 'selected' : '';
    if (!found && checked) {
      arraylist.splice(arraylist.indexOf(v), 1);
      found = true;
    }
    dropdown += `<option value="${v}" ${checked}>${v}</option>`;
  }
  dropdown += '</select>';
}
document.querySelector('div').innerHTML = dropdown
<div></div>

Related