¿Cómo eliminar todas las opciones de un cuadro de selección y luego agregar una opción y seleccionarla con jQuery?


Usando core jQuery, ¿cómo se eliminan todas las opciones de un cuadro de selección, luego se agrega una opción y se selecciona?

Mi cuadro de selección es el siguiente.

<Select id="mySelect" size="9" </Select>

EDITAR: El siguiente código fue útil con el encadenamiento. Sin embargo, (en Internet Explorer) .val('whatever') no seleccionó la opción que se agregó. (Usé el mismo' valor ' en .append y .val.)

$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');

EDITAR: Tratando de que imite este código, utilizo el siguiente código cada vez que se restablece la página/formulario. Este cuadro de selección se rellena con un conjunto de botones de opción. .focus() estaba más cerca, pero la opción no apareció seleccionada como lo hace con .selected= "true". Nada está mal con mi código existente-solo estoy tratando de aprender jQuery.

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";

EDITAR: la respuesta seleccionada estaba cerca de lo que necesitaba. Esto funcionó para mí:

$('#mySelect').children().remove().end().append('<option selected value="whatever">text</option>') ;

Pero ambas respuestas me llevaron a mi solución final..

Author: Martin Smith, 2008-09-07

21 answers

$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;
 1507
Author: Matt,
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
2008-10-17 02:25:14
$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;
 624
Author: Mahzilla,
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-04-08 14:24:08

¿Por qué no usar javascript simple?

document.getElementById("selectID").options.length = 0;
 109
Author: Shawn,
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-02-14 08:50:05

Tuve un error en IE7 (funciona bien en IE6) donde el uso de los métodos jQuery anteriores borraría el select en el DOM pero no en la pantalla. Usando la barra de herramientas para desarrolladores de IE, pude confirmar que el select se había borrado y tenía los nuevos elementos, pero visualmente el select todavía mostraba los elementos antiguos, aunque no pudo seleccionarlos.

La solución fue usar métodos/propiedades DOM estándar (como el original del póster) para borrar en lugar de jQuery-aún usando jQuery para añadir opciones.

$('#mySelect')[0].options.length = 0;
 72
Author: row1,
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-11 09:22:09

Si su objetivo es eliminar todas las opciones de la selección, excepto la primera (por lo general, la opción 'Elija un elemento'), podría usar:

$('#mySelect').find('option:not(:first)').remove();
 68
Author: mauretto,
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
2013-03-27 09:56:28
$('#mySelect')
    .empty()
    .append('<option value="whatever">text</option>')
    .find('option:first')
    .attr("selected","selected")
;
 24
Author: Hayden Chambers,
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
2009-06-03 20:48:14

No estoy seguro exactamente de lo que quiere decir con "añadir uno y seleccionarlo", ya que se seleccionará por defecto de todos modos. Pero, si agregaras más de uno, tendría más sentido. ¿Qué tal algo como:

$('select').children().remove();
$('select').append('<option id="foo">foo</option>');
$('#foo').focus();

Respuesta a"EDITAR" : ¿Puede aclarar lo que quiere decir con "Esta casilla de selección está poblada por un conjunto de botones de opción"? Un elemento .

 23
Author: Bobby Jack,
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
2008-09-08 22:28:36
$("#control").html("<option selected=\"selected\">The Option...</option>");
 20
Author: jvarandas,
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-03-30 02:30:23

Gracias a las respuestas que recibí, pude crear algo como lo siguiente, que se adapte a mis necesidades. Mi pregunta era algo ambigua. Gracias por el seguimiento. Mi problema final se resolvió mediante la inclusión de "seleccionado" en la opción que quería seleccionado.

$(function() {
  $('#mySelect').children().remove().end().append('<option selected value="One">One option</option>') ; // clear the select box, then add one option which is selected
  $("input[name='myRadio']").filter( "[value='1']" ).attr( "checked", "checked" ); // select radio button with value 1
  // Bind click event to each radio button.
  $("input[name='myRadio']").bind("click",
                                  function() {
    switch(this.value) {
      case "1":
        $('#mySelect').find('option').remove().end().append('<option selected value="One">One option</option>') ;
        break ;
      case "2":
        $('#mySelect').find('option').remove() ;
        var items = ["Item1", "Item2", "Item3"] ; // Set locally for demo
        var options = '' ;
        for (var i = 0; i < items.length; i++) {
          if (i==0) {
            options += '<option selected value="' + items[i] + '">' + items[i] + '</option>';
          }
          else {
            options += '<option value="' + items[i] + '">' + items[i] + '</option>';
          }
        }
        $('#mySelect').html(options);   // Populate select box with array
        break ;
    } // Switch end
  } // Bind function end
                                 ); // bind end
}); // Event listener end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>One<input  name="myRadio" type="radio" value="1"  /></label>
<label>Two<input name="myRadio"  type="radio" value="2" /></label>
<select id="mySelect" size="9"></select>
 10
Author: Jay Corbett,
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-08-24 11:41:38
  1. Primero borre toda la opción existente ejecute la primera (Select Select--)

  2. Añadir nuevos valores de opción usando bucle uno por uno

    $('#ddlCustomer').find('option:not(:first)').remove();
    for (var i = 0; i < oResult.length; i++) {
       $("#ddlCustomer").append(new Option(oResult[i].CustomerName, oResult[i].CustomerID + '/' + oResult[i].ID));
    }
    
 8
Author: Jaydeep Shil,
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
2017-08-07 12:19:17

¿Qué tal cambiar el html a nuevos datos?

$('#mySelect').html('<option value="whatever">text</option>');

Otro ejemplo:

$('#mySelect').html('
    <option value="1" selected>text1</option>
    <option value="2">text2</option>
    <option value="3" disabled>text3</option>
');
 7
Author: Shiv,
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-01 15:29:08

Otra manera:

$('#select').empty().append($('<option>').text('---------').attr('value',''));

En este enlace, hay buenas prácticas https://api.jquery.com/select/

 7
Author: Jhon Intriago Thoth,
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
2017-07-13 16:49:53

He encontrado en la red algo como a continuación. Con miles de opciones como en mi situación, esto es mucho más rápido que .empty() o .find().remove() de jQuery.

var ClearOptionsFast = function(id) {
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}

Más información aquí .

 6
Author: marioosh,
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
2015-04-08 09:42:42

Basándose en la respuesta de mauretto, esto es un poco más fácil de leer y entender:

$('#mySelect').find('option').not(':first').remove();

Para eliminar todas las opciones excepto una con un valor específico, puede usar esto:

$('#mySelect').find('option').not('[value=123]').remove();

Esto sería mejor si la opción a agregar ya estuviera allí.

 6
Author: humbads,
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
2015-06-18 13:52:28

Esto reemplazará su mySelect existente con una nueva mySelect.

$('#mySelect').replaceWith('<Select id="mySelect" size="9">
   <option value="whatever" selected="selected" >text</option>
   </Select>');
 4
Author: Barun,
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
2015-08-03 07:07:41

Puede hacerlo simplemente reemplazando html

$('#mySelect')
.html('<option value="whatever" selected>text</option>')
.trigger('change');
 4
Author: Nadeem Manzoor,
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-10-04 00:07:09

Usa jquery prop () para borrar la opción seleccionada

$('#mySelect option:selected').prop('selected', false);
 3
Author: mehrdad,
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-02-01 11:27:54

Espero que funcione

$('#myselect').find('option').remove()
.append($('<option></option>').val('value1').html('option1'));
 1
Author: Md. Russel Hussain,
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-10-23 04:06:55
  • guarde los valores de opción que se agregarán a un objeto
  • borrar las opciones existentes en la etiqueta select
  • itere el objeto list y añada el contenido a la etiqueta select deseada

var listToAppend = {'':'Select Vehicle','mc': 'Motor Cyle', 'tr': 'Tricycle'};

$('#selectID').empty();

$.each(listToAppend, function(val, text) {
    $('#selectID').append( new Option(text,val) );
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 1
Author: Nifemi Sola-Ojo,
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
2018-09-03 11:17:37
var select = $('#mySelect');
select.find('option').remove().end()
.append($('<option/>').val('').text('Select'));
var data = [{"id":1,"title":"Option one"}, {"id":2,"title":"Option two"}];
for(var i in data) {
    var d = data[i];
    var option = $('<option/>').val(d.id).text(d.title);
    select.append(option);
}
select.val('');
 0
Author: LN Nitharsan,
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
2018-08-19 17:38:08
$("#id option").remove();
$("#id").append('<option value="testValue" >TestText</option>');

La primera línea de código eliminará todas las opciones de un cuadro de selección, ya que no se ha mencionado ningún criterio de búsqueda de opción.

La segunda línea de código agregará la Opción con el valor especificado("testValue") y el Texto("TestText").

 -1
Author: Devkinandan Chauhan,
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
2018-10-12 10:59:19