Adding options to select with javascript

后端 未结 9 1147
执念已碎
执念已碎 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:54

    The most concise and intuitive way would be:

    var selectElement = document.getElementById('ageselect');
    
    for (var age = 12; age <= 100; age++) {
      selectElement.add(new Option(age));
    }
    Your age: 

    You can also differentiate the name and the value or add items at the start of the list with additional parameters to the used functions:
    HTMLSelect​Element​.add(item[, before]);
    new Option(text, value, defaultSelected, selected);

提交回复
热议问题