Cómo hacer la primera opción de seleccionado con jQuery


¿Cómo hago la primera opción de selected con jQuery?

<select id="target">
  <option value="1">...</option>
  <option value="2">...</option>
</select>
 473
Author: Peter Mortensen, 2009-09-12

25 answers

$("#target").val($("#target option:first").val());
 807
Author: David Andres,
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-09-12 04:31:42

Puedes probar esto

$("#target").prop("selectedIndex", 0);
 116
Author: Esben,
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-08-08 09:09:51
// remove "selected" from any options that might already be selected
$('#target option[selected="selected"]').each(
    function() {
        $(this).removeAttr('selected');
    }
);


// mark the first option as selected
$("#target option:first").attr('selected','selected');
 103
Author: user149513,
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-12-08 21:28:22

Cuando use

$("#target").val($("#target option:first").val());

Esto no funcionará en Chrome y Safari si el valor de la primera opción es null.

Prefiero

$("#target option:first").attr('selected','selected');

Porque puede funcionar en todos los navegadores.

 58
Author: Jimmy Huang,
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-01-08 14:13:02

Cambiar el valor de la entrada select o ajustar el atributo selected puede sobrescribir la propiedad selectedOptions predeterminada del elemento DOM, lo que resulta en un elemento que puede no restablecerse correctamente en un formulario al que se ha llamado el evento reset.

Use el método prop de jQuery para borrar y establecer la opción necesaria:

$("#target option:selected").prop("selected", false);
$("#target option:first").prop("selected", "selected");
 39
Author: James Lee Baker,
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-16 23:12:34
$("#target")[0].selectedIndex = 0;
 30
Author: danactive,
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-05-24 13:37:26

Un punto sutil que creo que he descubierto sobre las respuestas más votadas es que a pesar de que cambian correctamente el valor seleccionado, no actualizan el elemento que el usuario ve (solo cuando hacen clic en el widget verán una verificación junto al elemento actualizado).

Encadenamiento a .change () call to the end también actualizará el widget de interfaz de usuario también.

$("#target").val($("#target option:first").val()).change();

(Tenga en cuenta que noté esto mientras usaba jQuery Mobile y un cuadro en Chrome desktop, por lo que puede que no sea el caso en todas partes).

 17
Author: Bradley Bossard,
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-12-08 22:15:54

Si tiene opciones deshabilitadas, puede agregar not ([disabled]) para evitar seleccionarlas, lo que resulta en lo siguiente:

$("#target option:not([disabled]):first").attr('selected','selected')
 15
Author: Melanie,
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-01-08 14:13:32

Otra forma de restablecer los valores (para múltiples elementos seleccionados) podría ser esta:

$("selector").each(function(){

    /*Perform any check and validation if needed for each item */

    /*Use "this" to handle the element in javascript or "$(this)" to handle the element with jquery */

    this.selectedIndex=0;

});
 13
Author: Nick Petropoulos,
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-14 07:16:33

$('#newType option:first').prop('selected', true)

 7
Author: FFFFFF,
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-08-19 03:46:43

Así de simple:

$('#target option:first').prop('selected', true);
 7
Author: Ramon Schmidt,
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-19 09:27:12

He encontrado que solo establecer attr seleccionado no funciona si ya hay un atributo seleccionado. El código que utilizo ahora primero desajustará el atributo seleccionado y luego seleccionará la primera opción.

$('#target').removeAttr('selected').find('option:first').attr('selected', 'selected');
 6
Author: Francis Lewis,
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-09-16 06:02:10

Así es como lo haría:

$("#target option")
    .removeAttr('selected')
    .find(':first')     // You can also use .find('[value=MyVal]')
        .attr('selected','selected');
 5
Author: Fabrizio,
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-01-08 14:14:01

Aunque la función each probablemente no sea necesaria ...

$('select').each(function(){
    $(this).find('option:first').prop('selected', 'selected');
});

Funciona para mí.

 4
Author: Darth 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
2014-10-24 13:23:25

Si vas a usar la primera opción como un valor predeterminado como

<select>
    <option value="">Please select an option below</option>
    ...

Entonces puedes usar:

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

Es agradable y simple.

 2
Author: Gary - ITB,
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-01-08 14:14:35

Uso:

$("#selectbox option:first").val()

Por favor, encuentre el simple de trabajo en este JSFiddle.

 2
Author: Chetan,
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-01-08 14:15:21

En la parte posterior de la respuesta de James Lee Baker, prefiero esta solución, ya que elimina la dependencia del soporte del navegador para :first :selected ...

$('#target').children().prop('selected', false);
$($('#target').children()[0]).prop('selected', 'selected');
 1
Author: Matthew Scott,
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-18 15:30:43

Solo funcionó para mí usando un disparador ('change') al final, como esto:

$("#target option:first").attr('selected','selected').trigger('change');
 1
Author: Pablo S G Pacheco,
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-11-10 21:19:08

Para mí solo funcionó cuando agregué el siguiente código:

.change();

Para mí solo funcionó cuando agregué el siguiente código: Como quería "restablecer" el formulario, es decir, seleccionar todas las primeras opciones de todas las selecciones del formulario, utilicé el siguiente código:

$('form').find('select').each(function(){ $(this).val($("select option:first").val()); $(this).change(); });

 1
Author: Jean Douglas,
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-09-13 11:31:29
$("#target").val(null);

Funcionó bien en chrome

 0
Author: Krishna Murthy,
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-09-15 07:55:14

Si está almacenando el objeto jQuery del elemento select:

var jQuerySelectObject = $("...");

...

jQuerySelectObject.val(jQuerySelectObject.children().eq(0).val());
 0
Author: Daniel,
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-26 22:14:53

Uso:

alert($( "#target option:first" ).text());
 0
Author: GobsYats,
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-01-08 14:15:38

Compruebe este mejor enfoque usando jQuery con ECMAScript 6:

$('select').each((i, item) => {
  var $item = $(item);
  $item.val($item.find('option:first').val()); 
});
 0
Author: jdnichollsc,
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-01-08 14:17:58

Para mí, solo funcionó cuando agregué la siguiente línea de código

$('#target').val($('#target').find("option:first").val());
 0
Author: Muhammad Qasim,
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-06-11 07:46:42

Puede seleccionar cualquier opción de dropdown usándola.

// 'N' can by any number of option.  // e.g.,  N=1 for first option
$("#DropDownId").val($("#DropDownId option:eq(N-1)").val()); 
 0
Author: Arsman Ahmad,
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-07-04 07:02:34