Adding options to select with javascript

后端 未结 9 1107
执念已碎
执念已碎 2020-11-22 15:40

I want this javascript to create options from 12 to 100 in a select with id=\"mainSelect\", because I do not want to create all of the option tags manually. Can you give me

9条回答
  •  [愿得一人]
    2020-11-22 15:56

    Often you have an array of related records, I find it easy and fairly declarative to fill select this way:

    selectEl.innerHTML = array.map(c => '').join('');
    

    This will replace existing options.
    You can use selectEl.insertAdjacentHTML('afterbegin', str); to add them to the top instead.
    And selectEl.insertAdjacentHTML('beforeend', str); to add them to the bottom of the list.

    IE11 compatible syntax:

    array.map(function (c) { return ''; }).join('');
    

提交回复
热议问题