how to dynamically add options to an existing select in vanilla javascript

后端 未结 6 495
面向向阳花
面向向阳花 2020-11-29 20:16

I\'d like to add option to a select dynamically using plain javascript. Everything I could find involves JQuery or tries to create the select dynamically as well. The clos

相关标签:
6条回答
  • 2020-11-29 20:23

    Use the document.createElement function and then add it as a child of your select.

    var newOption = document.createElement("option");
    newOption.text = 'the options text';
    newOption.value = 'some value if you want it';
    daySelect.appendChild(newOption);
    
    0 讨论(0)
  • 2020-11-29 20:28

    Try this;

       var data = "";
       data = "<option value = Some value> Some Option </option>";         
       options = [];
       options.push(data);
       select = document.getElementById("drop_down_id");
       select.innerHTML = optionsHTML.join('\n'); 
    
    0 讨论(0)
  • 2020-11-29 20:30

    I guess something like this would do the job.

    var option = document.createElement("option");
    option.text = "Text";
    option.value = "myvalue";
    var select = document.getElementById("daySelect");
    select.appendChild(option);
    
    0 讨论(0)
  • 2020-11-29 20:40

    This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript

    Basically:

     daySelect = document.getElementById('daySelect');
     daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');
    
    0 讨论(0)
  • 2020-11-29 20:40

    The simplest way is:

    selectElement.add(new Option('Text', 'value'));
    

    Yes, that simple. And it works even in IE8. And has other optional parameters.

    See docs:

    • HTMLSelect​Element​.add(item[, before])
    • new Option(text, value, defaultSelected, selected);
    0 讨论(0)
  • 2020-11-29 20:41

    .add() also works.

    var daySelect = document.getElementById("myDaySelect");
    var myOption = document.createElement("option");
    myOption.text = "test";
    myOption.value = "value";
    daySelect.add(option);
    

    W3 School - try

    0 讨论(0)
提交回复
热议问题