简体   繁体   中英

How to set selected value for multiple dropdown

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.

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>

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