Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

html - Javascript Select Options all at Once

Is it possible to update all options of a <select> element at once?

Depending on a prior option selected, I would like

<select name="area" id="area" size="1" style="width: 150px"></select>

to change to (or something similar depending on the option selected):

<select name="area" id="area" size="1" style="width: 150px">
    <option selected="" disabled="">Select An Area/Resource</option>
    <option value="1">cafe</option>
    <option value="2">lounge</option>
    <option value="3" disabled="">quiet area</option>
    <option value="4">tables</option>
</select>

The block of options is actually stored in a variable as you see them here:

<option selected="" disabled="">Select An Area/Resource</option><option value="1">cafe</option><option value="2">lounge</option><option value="3" disabled="">quiet area</option><option value="4">tables</option>
question from:https://stackoverflow.com/questions/65645725/javascript-select-options-all-at-once

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure. It's just a matter of changing the .innerHTML of the select element.

const options = '<option selected="" disabled="">Select An Area/Resource</option><option value="1">cafe</option><option value="2">lounge</option><option value="3" disabled="">quiet area</option><option value="4">tables</option>';

const list = document.querySelector("select");

document.querySelector("input").addEventListener("click", function(){
  list.innerHTML = list.innerHTML === "" ? options : "";
});
<input type="checkbox">check or uncheck to change the following list.<br>
<select name="area" id="area" size="1" style="width: 150px"></select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...