tabla opciones lista dinamica desplegable años javascript html drop-down-menu html-select

javascript - opciones - ¿Cómo agregar la lista desplegable(<seleccionar>) programáticamente?



php lista desplegable dinamica (6)

Este código crearía una lista de selección de forma dinámica. Primero creo una matriz con los nombres de los automóviles. En segundo lugar, creo dinámicamente un elemento de selección y lo asigno a una variable "sEle" y lo adjunto al cuerpo del documento html. Luego utilizo un bucle for para recorrer la matriz. En tercer lugar, creo dinámicamente el elemento de opción y lo asigno a una variable "oEle". Utilizando una declaración if, asigno los atributos ''disabled'' y ''selected'' al primer elemento de opción [0] para que se seleccione siempre y esté desactivado. Luego creo una matriz de nodos de texto "oTxt" para anexar los nombres de la matriz y luego anexar el nodo de texto al elemento de opción que luego se agrega al elemento de selección.

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

Quiero crear una función para agregar elementos de una página por medio de una programación.

Digamos que quiero agregar una lista desplegable con cuatro opciones:

<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>

¿Cómo puedo hacer eso?


Esto funcionará (JS puro, que se agrega a un div de id myDiv ):

var myDiv = document.getElementById("myDiv"); //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"; myDiv.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); }

Demostración: http://jsfiddle.net/4pwvg/


Rápidamente he hecho una función que puede lograr esto, puede que no sea la mejor manera de hacerlo, pero simplemente funciona y debe ser un navegador cruzado, también sé que NO soy un experto en JavaScript, así que cualquier consejo es genial :)

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; }

veamos cómo hacemos esto

<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>

Así es como funciona

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 # );

este es el 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'');

Esta función sería adecuada si tiene que agregar muchos elementos, si hay alguna forma de mejorar esta respuesta, por favor hágamelo saber.

editar:

Aquí hay una demostración funcional

Demostración de JSFiddle

¡Esto puede ser altamente personalizado para adaptarse a su proyecto!


es muy simple pero complicado, pero esto es lo que quería, espero que sea útil: esta función genera una lista de selección de 1990 a 2018, creo que este ejemplo puede ayudarlo, si desea agregar cualquier otro valor, simplemente cambie el valor de xey; )

function test(){ var x = 1990; var y = 2018; document.write("<select>"); for (var i = x; i <= y; i++) document.write("<option>" + i + "</option>"); } document.write("</select>"); test();


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); }


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); };