usar jquery para seleccionar una opción desplegable


Me preguntaba si es posible obtener jQuery para seleccionar una opción, por ejemplo, el 4to elemento, en un cuadro desplegable?

<select>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
    <option></option>
</select>

Quiero que el usuario haga clic en un enlace, luego haga que el cuadro de selección cambie su valor, como si el usuario lo hubiera seleccionado haciendo clic en la opción.

Author: Ionică Bizău, 2011-02-01

13 answers

¿Qué tal

$('select>option:eq(3)').attr('selected', true);

Ejemplo en http://www.jsfiddle.net/gaby/CWvwn/


Para las versiones modernas de jquery debe utilizar el .prop() en lugar de .attr()

$('select>option:eq(3)').prop('selected', true);

Ejemplo en http://jsfiddle.net/gaby/CWvwn/1763/

 153
Author: Gabriele Petrioli,
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-05-13 09:31:50

La solución:

$("#element-id").val('the value of the option');
 130
Author: Harold SOTA,
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-03-30 21:39:44

Los elementos HTML select tienen selectedIndex propiedad en la que se puede escribir para seleccionar una opción en particular:

$('select').prop('selectedIndex', 3); // select 4th option

Usando JavaScript simple esto se puede lograr mediante:

// use first select element
var el = document.getElementsByTagName('select')[0]; 
// assuming el is not null, select 4th option
el.selectedIndex = 3;
 41
Author: Ja͢ck,
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-02-28 00:43:05

La forma más fácil es val(value) función:

$('select').val(2);

Y para obtener el valor seleccionado no da argumentos:

$('select').val();

También, si tienes <option value="valueToSelect">...</option>, puedes hacer:

$('select').val("valueToSelect");

DEMO

 20
Author: Ionică Bizău,
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-10-14 05:12:21

Si sus opciones tienen un valor, puede hacer esto:

$('select').val("the-value-of-the-option-you-want-to-select");

'select' sería el id de su select o un selector de clase. o si solo hay una selección, puede usar la etiqueta tal como está en el ejemplo.

 19
Author: Victor,
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-02-01 15:47:08

Lo haría de esta manera

 $("#idElement").val('optionValue').trigger('change');
 10
Author: franzisk,
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-11-05 10:21:59

Utilice el siguiente código si desea seleccionar una opción con un valor específico:

$('select>option[value="' + value + '"]').prop('selected', true);
 6
Author: nlareu,
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-21 14:46:32

Prefiero nth-child() a eq (), ya que usa la indexación basada en 1 en lugar de la basada en 0, lo que es ligeramente más fácil para mi cerebro.

//selects the 2nd option
$('select>option:nth-child(2)').attr('selected', true);
 3
Author: Lee D,
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-02-01 15:50:47

Con " element usualmente usamos el atributo 'value'. Esto hará que sea más fácil de establecer entonces:

$('select').val('option-value');
 3
Author: Savaratkar,
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-11-21 10:59:35

Prueba esto:

$('#mySelectElement option')[0].selected = true;

Saludos!

 3
Author: Nicolas Finelli,
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-12-02 14:20:33

Respuesta con id:

$('#selectBoxId').find('option:eq(0)').attr('selected', true);
 2
Author: Javad Masoumi,
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-12-22 11:51:52
 Try with the below codes. All should work. 
    $('select').val(2);
    $('select').prop('selectedIndex', 1);
    $('select>option[value="5"]').prop('selected', true);
    $('select>option:eq(3)').attr('selected', 'selected');
    $("select option:contains(COMMERCIAL)").attr('selected', true);
 2
Author: Mamun Rasid,
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-03 10:12:05
 $('select>option:eq(3)').attr('selected', 'selected');

Una advertencia aquí es que si tiene javascript observando el evento de cambio de select/option, debe agregar .trigger('change') para que el código se convierta.

 $('select>option:eq(3)').attr('selected', 'selected').trigger('change');

Porque solo llamar a .attr('selected', 'selected') no activa el evento

 0
Author: kanitw,
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-05-27 17:56:21