Crear dinámicamente con Javascript select con optgroup

Supongamos que tenemos un array de objetos javascript. Cada objeto tiene tres propiedades: cod, tex, grupo.
Estos objetos son los elementos que queremos representar en un SELECT, y agrupados en OPTGROUPS.

Código:

var grupo_anterior="";var grupo;var opcion;

for (var i in array_options){    if(grupo_anterior!=array_options[i].grupo){        //reconocido nuevo grupo
        grupo          = document.createElement('OPTGROUP');        grupo.label    = array_options[i].grupo;        grupo_anterior = array_options[i].grupo;        select.appendChild(grupo);    }    opcion = document.createElement("OPTION");    opcion.setAttribute("value",array_options[i].cod);    //se le pone el texto visible
    opcion.innerHTML = array_options[i].tex;    //se incluye en el grupo
    select.appendChild(opcion);}

Este código sería lo fundamental para entender cómo funciona. Ha quedado pendiente la variable select, que representa el objeto select en el que inclñuiremos las opciones. Éste es necesario tomarlo, por ejemplo a partir del id con getElementById, o bien pasándolo como parámetro a la función en la que incluyamos este código.
Aquí un ejemplo completo que funciona y se puede probar copiandolo en una página html:

<script>

function Objeto(cod,tex,grupo){  this.cod=cod;  this.tex=tex;  this.grupo=grupo;}

function pintaOptions(){

  var select = document.getElementById('prueba');

  var array_options = new Array();  array_options['a'] = new Objeto('1','elemento 1','grupo1');  array_options['b'] = new Objeto('2','elemento 2','grupo1');  array_options['c'] = new Objeto('3','elemento 3','grupo2');  array_options['d'] = new Objeto('4','elemento 4','grupo2');

  var grupo_anterior="";  var grupo;  var opcion;

  for (var i in array_options){    if(grupo_anterior!=array_options[i].grupo){      grupo          = document.createElement('OPTGROUP');      grupo.label    = array_options[i].grupo;      grupo_anterior = array_options[i].grupo;      select.appendChild(grupo);    }    opcion = document.createElement("OPTION");    opcion.setAttribute("value",array_options[i].cod);    opcion.innerHTML = array_options[i].tex;    select.appendChild(opcion);  }}

</script>

<select id="prueba">    <script>pintaOptions();</script></select>

El resultado es:

One Response to “Crear dinámicamente con Javascript select con optgroup”

  1. 2012 Fashion ideas k…

    I guess what I’m trying to say is, I don’t think you can measure life in terms of years. I think longevity doesn’t necessarily have anything to do with happiness. I mean happiness comes from facing challenges and going out on a limb and taking risks…

Leave a Response

You must be logged in to post a comment.