How to add Drop-Down list (<select>) programmatically?

前端 未结 9 2168
北恋
北恋 2020-11-27 14:12

I want to create a function in order to programmatically add some elements on a page.

Lets say I want to add a drop-down list with four options:

<         


        
相关标签:
9条回答
  • 2020-11-27 14:36

    This code would create a select list dynamically. First I create an array with the car names. Second, I create a select element dynamically and assign it to a variable "sEle" and append it to the body of the html document. Then I use a for loop to loop through the array. Third, I dynamically create the option element and assign it to a variable "oEle". Using an if statement, I assign the attributes 'disabled' and 'selected' to the first option element [0] so that it would be selected always and is disabled. I then create a text node array "oTxt" to append the array names and then append the text node to the option element which is later appended to the select element.

    var array = ['Select Car', 'Volvo', 'Saab', 'Mervedes', 'Audi'];
    
    var sEle = document.createElement('select');
    document.getElementsByTagName('body')[0].appendChild(sEle);
    
    for (var i = 0; i < array.length; ++i) {
      var oEle = document.createElement('option');
    
      if (i == 0) {
        oEle.setAttribute('disabled', 'disabled');
        oEle.setAttribute('selected', 'selected');
      } // end of if loop
    
      var oTxt = document.createTextNode(array[i]);
      oEle.appendChild(oTxt);
    
      document.getElementsByTagName('select')[0].appendChild(oEle);
    } // end of for loop

    0 讨论(0)
  • Here's an ES6 version of the answer provided by 7stud.

    const sel = document.createElement('select');
    sel.name = 'drop1';
    sel.id = 'Select1';
    
    const cars = [
      "Volvo",
      "Saab",
      "Mercedes",
      "Audi",
    ];
    
    const options = cars.map(car => {
      const value = car.toLowerCase();
      return `<option value="${value}">${car}</option>`;
    });
    
    sel.innerHTML = options;
    
    window.onload = () => document.body.appendChild(sel);
    
    0 讨论(0)
  • 2020-11-27 14:39

    it's very simple yet tricky but here is what you wanted, hope it's helpful : this function generates a select list from 1990 to 2018 i think this example can help ya, if you want to add any other value just change value of x and y ;)

    function dropDown(){
        var start = 1990;
        var today = 2019;
        document.write("<select>");
        for (var i = start ; i <= today; i++)
        document.write("<option>" + i + "</option>");
    }
    document.write("</select>");
    
    dropDown();
    
    0 讨论(0)
提交回复
热议问题