javascriptarrayshtml-selecthtmlcollection

How would i add more values in a option element with JS?


If someone could help me out with coding in JS. I have a Select element with some Option values created in a HTML, also below i have a input field where i want to be able to add a a new Option value and also delete if i need to. I know that this could be achived trough the looping i guess, but since the DOM gives me a HTMLcollection of the elements of the Option list.So i know that i can achive that with the createELement in the DOM , but is it possible to do that different. My code is this below:

<select name="name" id="name">

    <option value="burim" class="someName">burim</option>
    <option value="eliot" class="someName">eliot</option>
    <option value="saska" class="someName">saska</option>

</select>
<br><br>
<input type="text" id="add">
<br><br>
<p class="output"></p>

Solution

  • Here is the basic code :

    let select = document.getElementById("mySelect");
    let option = document.createElement("option");
    option.text = "Starwars 8";
    option.value = "Starwars 8"
    select.add(option);
    

    Do you need more : adding a listener on "#add" ?