¿La mejor manera de deseleccionar una en jQuery?


<select size="2">
<option selected="selected">Input your option</option>
<option>Input your option</option>
</select>

¿Cuál es la mejor manera, usando jQuery, de deseleccionar elegantemente la opción?

 190
Author: Dave Liepmann, 2009-12-07

13 answers

Use removeAttr...

$("option:selected").removeAttr("selected");

O Prop

$("option:selected").prop("selected", false)
 307
Author: Ei Maung,
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-06-25 19:59:59

Hay muchas respuestas aquí, pero desafortunadamente todas ellas son bastante antiguas y, por lo tanto, dependen de attr/removeAttr que en realidad no es el camino a seguir.

@coffeeyesplease menciona correctamente que una buena solución entre navegadores es usar

$("select").val([]);

Otra buena solución cross-browser es

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

Puede ver que ejecuta un auto-test aquí. Probado en IE 7/8/9, FF 11, Cromo 19.

 140
Author: Jon,
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-06-19 10:20:12

Ha pasado un tiempo desde que se preguntó, y no he probado esto en navegadores más antiguos, pero me parece una respuesta mucho más simple es

$("#selectID").val([]);

.val () también funciona para select http://api.jquery.com/val /

 21
Author: coffeeyesplease,
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-05-13 13:28:41

Las respuestas hasta ahora solo funcionan para múltiples selecciones en IE6 / 7; para la selección no múltiple más común, debe usar:

$("#selectID").attr('selectedIndex', '-1');

Esto se explica en el post enlazado por flyfishr64. Si lo miras, verás cómo hay 2 casos-multi / non-multi. No hay nada que te detenga chaning tanto para una solución completa:

$("#selectID").attr('selectedIndex', '-1').find("option:selected").removeAttr("selected");
 19
Author: thetoolman,
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-06-03 10:51:25

Método más simple

$('select').val('')

Simplemente usé esto en el select y funcionó.

Estoy en jQuery 1.7.1.

 18
Author: Joshua Pinter,
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 17:44:45

Un rápido google encontró este post que describe cómo hacer lo que desea para ambas listas de selección única y múltiple en IE. La solución también parece bastante elegante:

$('#clickme').click(function() {
        $('#selectmenu option').attr('selected', false);

}); 
 5
Author: Jeff Paquette,
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-12-07 04:25:39
$("#selectID option:selected").each(function(){
  $(this).removeAttr("selected");
});

Esto iterar a través de cada elemento y anule la selección de sólo los que se comprueban

 5
Author: DinoMyte,
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-08-15 21:17:58

Oh jquery.

Dado que todavía hay un enfoque nativo de javascript, siento la necesidad de proporcionar uno.

var select = document.querySelector('select'); //hopefully you'll use a better selector query
select.selectedIndex = 0; // or -1, 0 sets it to first option, -1 selects no options

Y solo para mostrarte cuánto más rápido es esto: benchmark

 4
Author: Blaine Kasten,
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-08-08 21:25:57
$(option).removeAttr('selected') //replace 'option' with selected option's selector
 3
Author: Brandon H,
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-12-07 04:25:31
$("option:selected").attr("selected", false);
 2
Author: Charlie Brown,
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-12-07 04:27:05

Muchas Gracias por la solución.

La solución para la lista combinada de opción única funciona perfectamente. Encontré esto después de buscar en muchos sitios.

$("#selectID").attr('selectedIndex', '-1').children("option:selected").removeAttr("selected");
 2
Author: Madeswaran Govindan,
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-20 12:12:42

Por lo general, cuando uso un menú de selección, cada opción tiene un valor asociado. Por ejemplo

<select id="nfl">
  <option value="Bears Still...">Chicago Bears</option>
  <option selected="selected" value="Go Pack">Green Bay Packers</option>
</select>
console.log($('#nfl').val()) logs "Go Pack" to the console
Set the value to an empty string $('#nfl').val("")
console.log($('#nfl').val()) logs "" to the console

Ahora bien, esto no elimina el atributo seleccionado de la opción, pero todo lo que realmente quiero es el valor.

 1
Author: jtaz,
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-05-13 13:51:43

Otra manera simple:

$("#selectedID")[0].selectedIndex = -1

 1
Author: Rafael,
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-01-18 23:06:27