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

前端 未结 9 2167
北恋
北恋 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:12

    This will work (pure JS, appending to a div of id myDiv):

    Demo: http://jsfiddle.net/4pwvg/

    var myParent = document.body;
    
    //Create array of options to be added
    var array = ["Volvo","Saab","Mercades","Audi"];
    
    //Create and append select list
    var selectList = document.createElement("select");
    selectList.id = "mySelect";
    myParent.appendChild(selectList);
    
    //Create and append the options
    for (var i = 0; i < array.length; i++) {
        var option = document.createElement("option");
        option.value = array[i];
        option.text = array[i];
        selectList.appendChild(option);
    }

    0 讨论(0)
  • 2020-11-27 14:14

    I have quickly made a function that can achieve this, it may not be the best way to do this but it simply works and should be cross browser, please also know that i am NOT a expert in JavaScript so any tips are great :)

    Pure Javascript Create Element Solution

    function createElement(){
        var element  = document.createElement(arguments[0]),
            text     = arguments[1],
            attr     = arguments[2],
            append   = arguments[3],
            appendTo = arguments[4];
    
        for(var key = 0; key < Object.keys(attr).length ; key++){
            var name = Object.keys(attr)[key],
                 value = attr[name],
                 tempAttr = document.createAttribute(name);
                 tempAttr.value = value;
            element.setAttributeNode(tempAttr)
        }
        
        if(append){
            for(var _key = 0; _key < append.length; _key++) {
                element.appendChild(append[_key]);
            }
        }
    
        if(text) element.appendChild(document.createTextNode(text));
    
        if(appendTo){
            var target = appendTo === 'body' ? document.body : document.getElementById(appendTo);
            target.appendChild(element)
        }       
    
        return element;
    }
    

    lets see how we make this

    <select name="drop1" id="Select1">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>
    

    here's how it works

        var options = [
            createElement('option', 'Volvo', {value: 'volvo'}),
            createElement('option', 'Saab', {value: 'saab'}),
            createElement('option', 'Mercedes', {value: 'mercedes'}),
            createElement('option', 'Audi', {value: 'audi'})
        ];
    
    
        createElement('select', null, // 'select' = name of element to create, null = no text to insert
            {id: 'Select1', name: 'drop1'}, // Attributes to attach
            [options[0], options[1], options[2], options[3]], // append all 4 elements
            'body' // append final element to body - this also takes a element by id without the #
        );
    

    this is the params

    createElement('tagName', 'Text to Insert', {any: 'attribute', here: 'like', id: 'mainContainer'}, [elements, to, append, to, this, element], 'body || container = where to append this element');
    

    This function would suit if you have to append many element, if there is any way to improve this answer please let me know.

    edit:

    Here is a working demo

    JSFiddle Demo

    This can be highly customized to suit your project!

    0 讨论(0)
  • 2020-11-27 14:18
    const countryResolver = (data = [{}]) => {
        const countrySelecter = document.createElement('select');
        countrySelecter.className = `custom-select`;
        countrySelecter.id = `countrySelect`;
        countrySelecter.setAttribute("aria-label", "Example select with button addon");
    
        let opt = document.createElement("option");
        opt.text = "Select language";
        opt.disabled = true;
        countrySelecter.add(opt, null);
        let i = 0;
        for (let item of data) {
            let opt = document.createElement("option");
            opt.value = item.Id;
            opt.text = `${i++}. ${item.Id} - ${item.Value}(${item.Comment})`;
            countrySelecter.add(opt, null);
        }
        return countrySelecter;
    };
    
    0 讨论(0)
  • 2020-11-27 14:28
    var sel = document.createElement('select');
    sel.name = 'drop1';
    sel.id = 'Select1';
    
    var cars = [
      "volvo",
      "saab",
      "mercedes",
      "audi"
    ];
    
    var options_str = "";
    
    cars.forEach( function(car) {
      options_str += '<option value="' + car + '">' + car + '</option>';
    });
    
    sel.innerHTML = options_str;
    
    
    window.onload = function() {
      document.body.appendChild(sel);
    };
    
    0 讨论(0)
  • 2020-11-27 14:28

    Here's an ES6 version, conversion to vanilla JS shouldn't be too hard but I already have jQuery anyways:

    function select(options, selected) {
      return Object.entries(options).reduce((r, [k, v]) => r.append($('<option>').val(k).text(v)), $('<select>')).val(selected);
    }
    $('body').append(select({'option1': 'label 1', 'option2': 'label 2'}, 'option2'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

    0 讨论(0)
  • 2020-11-27 14:29

    const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];
    
    let domSelect = document.createElement('select');
    domSelect.multiple = true;
    document.getElementsByTagName('body')[0].appendChild(domSelect);
    
    
    for (const i in cars) {
      let optionSelect = document.createElement('option');
    
      let optText = document.createTextNode(cars[i]);
      optionSelect.appendChild(optText);
    
      document.getElementsByTagName('select')[0].appendChild(optionSelect);
    }

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