¿Cómo puedo añadir opciones a una lista desplegable usando jQuery?


Como dice la pregunta, ¿cómo agrego una nueva opción a una lista desplegable usando jQuery?

Gracias

Author: Earlz, 2008-11-25

11 answers

Sin usar ningún complemento adicional,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

Si tiene muchas opciones, o este código necesita ejecutarse con mucha frecuencia, entonces debe buscar usar un DocumentFragment en lugar de modificar el DOM muchas veces innecesariamente. Por solo un puñado de opciones, diría que no vale la pena.

------------------------------- Agregó --------------------------------

DocumentFragment es una buena opción para la mejora de la velocidad, pero no podemos crear elemento de opción usando document.createElement('option') desde IE6 y IE7 no lo están apoyando.

Lo que podemos hacer es crear un nuevo elemento select y luego añadir todas las opciones. Una vez finalizado el bucle, añádalo al objeto DOM real.

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
    _select.append(
            $('<option></option>').val(val).html(text)
        );
});
$('#mySelect').append(_select.html());

De esta manera vamos a modificar DOM por una sola vez!

 445
Author: nickf,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-18 08:09:16

Sin plug-ins, esto puede ser más fácil sin usar tanto jQuery, en lugar de ir un poco más de la vieja escuela:

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
$.each(myOptions, function(val, text) {
    $('#mySelect').append( new Option(text,val) );
});

Si desea especificar si la opción a) es el valor seleccionado por defecto, y b) debe seleccionarse ahora, puede pasar dos parámetros más:

    var defaultSelected = false;
    var nowSelected     = true;
    $('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );
 159
Author: Phrogz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-10 14:49:38

Con el plugin: jQuery Selection Box. Puedes hacer esto:

var myOptions = {
        "Value 1" : "Text 1",
        "Value 2" : "Text 2",
        "Value 3" : "Text 3"
    }
    $("#myselect2").addOption(myOptions, false); 
 13
Author: cgreeno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-12 17:47:05

Es posible que desee borrar su menú desplegable primero $('#DropDownQuality').vacío();

Hice que mi controlador en MVC devolviera una lista de selección con un solo elemento.

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    
 9
Author: Har,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-23 20:42:21

Añadir elemento a la lista en el comienzo

$("#ddlList").prepend('<option selected="selected" value="0"> Select </option>');

Añadir elemento a la lista al final

$('<option value="6">Java Script</option>').appendTo("#ddlList");

Operación desplegable común (Get, Set, Add, Remove) usando jQuery

 7
Author: Zakaria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-03 06:59:37

Nota Pease La solución de @Phrogz no funciona en IE 8 mientras que @nickf funciona en todos los navegadores principales. Otro enfoque es:

$.each(myOptions, function(val, text) {
    $("#mySelect").append($("&lt;option/&gt;").attr("value", val).text(text));
});
 4
Author: Marshal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-08-22 01:15:10

U puede usar direct

$"(.ddlClassName").Html("<option selected=\"selected\" value=\"1\">1</option><option value=\"2\">2</option>")

- > Aquí u puede usar cadena directa

 3
Author: Jay,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-20 09:14:41

Y también, use.prepend() para añadir la opción al inicio de la lista de opciones. http://api.jquery.com/prepend /

 3
Author: Johan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-03-29 05:51:08

Usando jquery puedes usar

      this.$('select#myid').append('<option>newvalue</option>');

Donde "myid" es la id de la lista desplegable y newvalue es el texto que desea insertar..

 0
Author: chopss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-12 09:44:20

Necesitaba agregar tantas opciones a los menús desplegables como había en mi página. Así que lo usé de esta manera:

function myAppender(obj, value, text){
    obj.append($('<option></option>').val(value).html(text));
}

$(document).ready(function() {
    var counter = 0;
    var builder = 0;
    // Get the number of dropdowns
    $('[id*="ddlPosition_"]').each(function() {
        counter++;
    });

    // Add the options for each dropdown
    $('[id*="ddlPosition_"]').each(function() {
        var myId = this.id.split('_')[1];

        // Add each option in a loop for the specific dropdown we are on
        for (var i=0; i<counter; i++) {
            myAppender($('[id*="ddlPosition_'+myId+'"]'), i, i+1);
        }
        $('[id*="ddlPosition_'+myId+'"]').val(builder);
        builder++;
    });
});

Esto configura dinámicamente menús desplegables con valores como 1 a n, y selecciona automáticamente el valor para el orden en el que se encuentra el menú desplegable (es decir, el 2do menú desplegable tiene "2" en el cuadro, etc.).

Era ridículo que no pudiera usar this o this.Object o $.obj ni nada parecido en mi 2do .each(), aunque - - - Realmente tuve que obtener el ID específico de ese objeto y luego agarra y pasa todo ese objeto a mi función antes de que se anexe. Afortunadamente el ID de mi menú desplegable estaba separado por un " _ " y pude agarrarlo. No siento que debería haber tenido que hacerlo, pero me siguió dando excepciones jQuery de lo contrario. Algo que otros que luchan con lo que yo era podrían disfrutar sabiendo.

 0
Author: vapcguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-20 02:51:46

Prueba esta función:

function addtoselect(param,value){
    $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');
}
 -1
Author: Sebastian Mach,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-23 20:51:02