Restablecer el valor select2 y mostrar marcador de posición


Cómo establezco el marcador de posición en el valor reset por select2. En mi ejemplo, si se hace clic en ubicaciones o cuadros de selección de calificación y mi select2 tiene un valor que el valor de select2 debe restablecer y mostrar el marcador de posición predeterminado. Este script está restableciendo el valor pero no mostrará el marcador de posición

$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});
Author: Hakam Fostok, 2013-07-31

29 answers

Debe definir la select2 como

$("#customers_select").select2({
    placeholder: "Select a customer",
    initSelection: function(element, callback) {                   
    }
});

Para restablecer la selección2

$("#customers_select").select2("val", "");
 188
Author: AbdelMalek,
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-24 15:20:14

Select2 ha cambiado su API:

Select2: El método select2("val") ha quedado obsoleto y se eliminará en versiones posteriores de Select2. Usa element element.val() en su lugar.

La mejor manera de hacer esto ahora es:

$('#your_select_input').val('');

Editar: Diciembre 2016 Los comentarios sugieren que la siguiente es la forma actualizada de hacer esto:

$('#your_select_input').val([]);
 98
Author: Hakam Fostok,
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-24 15:17:33

La respuesta aceptada no funciona en mi caso. Estoy intentando esto, y está funcionando:

Define select2:

$("#customers_select").select2({
    placeholder: "Select a State",
    allowClear: true
});

O

$("#customers_select").select2({
    placeholder: "Select a State"
});

Para restablecer:

$("#customers_select").val('').trigger('change')

O

$("#customers_select").empty().trigger('change')
 74
Author: NorthCat,
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-03-03 14:06:20

Lo único que puede funcionar para mí es:

$('select2element').val(null).trigger("change")

Estoy usando la versión 4.0.3

Referencia

Según la documentación de Select2

 23
Author: M.Tae,
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-08 00:12:13

Select2 utiliza una clase CSS específica, por lo que una forma fácil de restablecerla es:

$('.select2-container').select2('val', '');

Y tiene la ventaja de que si tiene múltiples Select2 en el mismo formulario, todos ellos se reiniciarán con este único comando.

 14
Author: Marcio Mazzucato,
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-01 15:42:06

Usa esto:

$('.select').val([]).trigger('change');
 13
Author: Sachin Gend,
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-29 08:06:02

PARA ELIMINAR EL VALOR SELECCIONADO

$('#employee_id').select2('val','');

PARA BORRAR LOS VALORES DE LAS OPCIONES

$('#employee_id').html('');
 8
Author: Shanka SMS,
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-07-23 07:52:18

Sé que esta es una vieja pregunta, pero esto funciona para la versión 4.0 de select2

 $('#select2-element').val('').trigger('change');

O

$('#select2-element').val('').trigger('change.select2'); 

Si tiene eventos de cambio vinculados a él

 6
Author: Sean,
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-03-02 02:42:07

Primero debes definir select2 así:

$('#id').select2({
    placeholder: "Select groups...",
    allowClear: true,
    width: '100%',
})

Para restablecer select2, simplemente puede usar el siguiente bloque de código:

$("#id > option").removeAttr("selected");
$("#id").trigger("change");
 5
Author: Mahmut Aydın,
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-23 22:08:59

Puede borrar la selección mediante

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

Pero no te volverá a tu marcador de posición.

Así que es una solución media

 4
Author: Rodrigo Butta,
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-12-04 14:52:18

Este es el camino correcto:

 $("#customers_select").val('').trigger('change');

Estoy utilizando la última versión de Select2.

 4
Author: TreeZ,
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-05-15 10:55:34

Para los usuarios que cargan datos remotos, este restablecerá el select2 al marcador de posición sin disparar ajax. Funciona con v4.0. 3:

$("#lstProducts").val("").trigger("change.select2");
 3
Author: Chad Kuehn,
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-31 23:11:49

Utilice lo siguiente para configurar select2

    $('#selectelementid').select2({
        placeholder: "Please select an agent",
        allowClear: true // This is for clear get the clear button if wanted 
    });

Y para borrar la selección de entrada mediante programación

    $("#selectelementid").val("").trigger("change");
    $("#selectelementid").trigger("change");
 3
Author: The Programmer- Zabith Rafeek,
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-02 12:05:13

Siguiendo la recomendada forma de hacerlo. Encontrado en la documentación https://select2.github.io/options.html#my-first-option-is-being-displayed-instead-of-my-placeholder (esto parece ser un problema bastante común):

Cuando esto sucede, generalmente significa que no tiene un <option></option> en blanco como primera opción en su <select>.

Como en:

<select>
   <option></option>
   <option value="foo">your option 1</option>
   <option value="bar">your option 2</option>
   <option value="etc">...</option>
</select>
 2
Author: fmsf,
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-03-30 12:22:12

También estaba teniendo este problema y se deriva de val(null).trigger("change"); lanzando un error No select2/compat/inputData antes de que el marcador de posición se restablezca. Lo resolví capturando el error y estableciendo el marcador de posición directamente (junto con un ancho). Nota: Si tiene más de uno, tendrá que atrapar a cada uno.

try{
    $("#sel_item_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
try{
    $("#sel_location_ID").select2().val(null).trigger("change");
}catch(err){
    console.debug(err)
}
$('.select2-search__field')[0].placeholder='All Items';
$('.select2-search__field')[1].placeholder='All Locations';
$('.select2-search__field').width(173);

Estoy ejecutando Select2 4.0.3

 2
Author: Aba,
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-03-23 21:03:38

He intentado soluciones anteriores, pero ninguna funcionó con la versión 4x.

Lo que quiero lograr es: borrar todas las opciones pero no tocar el marcador de posición. Este código funciona para mí.

selector.find('option:not(:first)').remove().trigger('change');
 1
Author: R. Canser Yanbakan,
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-03-14 13:26:35

Probé las soluciones anteriores, pero no funcionó para mí.

Esto es una especie de hackeo, donde no tienes que activar el cambio.

$("select").select2('destroy').val("").select2();

O

$("select").each(function () { //added a each loop here
        $(this).select2('destroy').val("").select2();
});
 1
Author: tech_boy,
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-04-12 10:47:23

Usando select2 versión 3.2 esto funcionó para mí:

$('#select2').select2("data", "");

No necesitaba implementar initSelection

 1
Author: shak,
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-04-29 17:32:38

a partir de v. 4. 0.x...

Para borrar los valores, pero también restaurar el uso de marcador de posición...

.html('<option></option>');  // defaults to placeholder

Si está vacío, seleccionará el primer elemento de opción que puede no ser lo que desea

.html(''); // defaults to whatever item is first

, Francamente...Select2 es un dolor en el trasero, me sorprende que no haya sido reemplazado.

 1
Author: mangonights,
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-04 02:23:10

Para el titular de la plaza

$("#stateID").select2({
    placeholder: "Select a State"
});

Para restablecer un select 2

$('#stateID').val('');
$('#stateID').trigger('change');

Espero que esto ayude

 1
Author: Rinto George,
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-05-09 06:22:46

Antes de borrar el valor usando este $("#customers_select").select2("val", ""); Intente ajustar el enfoque a cualquier otro control al hacer clic en restablecer.

Esto mostrará el marcador de posición de nuevo.

 0
Author: user2243380,
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-12 20:24:26

La interfaz DOM, ya realiza un seguimiento del estado inicial...

Así que hacer lo siguiente es suficiente:

$("#reset").on("click", function () {
    $('#my_select option').prop('selected', function() {
        return this.defaultSelected;
    });
});
 0
Author: Andrew Nartey,
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-06-21 09:27:10

Bueno, cada vez que lo hice

$('myselectdropdown').select2('val', '').trigger('change');

Empecé a tener algún tipo de retraso después de unos tres o cuatro desencadenantes. Supongo que hay una fuga de memoria. No está dentro de mi código porque si elimino esta línea, mi aplicación está libre de retrasos.

Dado que tengo las opciones allowClear establecidas en true, fui con

$('.select2-selection__clear').trigger('mousedown');

Esto puede ser seguido por un $('myselectdropdown').select2 ('close'); activador de eventos en el elemento select2 dom en caso de que desee cerrar el menú desplegable abrir sugerencia.

 0
Author: Akhilesh Balachandder,
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-29 05:58:19

Una manera [muy] hacky de hacerlo (vi que funciona para la versión 4.0.3):

var selection = $("#DelegateId").data("select2").selection;
var evt = document.createEvent("UIEvents");
selection._handleClear(evt);
selection.trigger("toggle", {});
  • allowClear debe ponerse en true
  • una opción vacía debe existir en el elemento select
 0
Author: Ellery Newcomer,
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-31 18:38:32

Después de probar las primeras 10 soluciones aquí y fallar, encontré esta solución para trabajar (ver "nilov comentó el 7 de abril * editado" comentario en la página):

(function ($) {
   $.fn.refreshDataSelect2 = function (data) {
       this.select2('data', data);

       // Update options
       var $select = $(this[0]);
       var options = data.map(function(item) {
           return '<option value="' + item.id + '">' + item.text + '</option>';
       });
       $select.html(options.join('')).change();
   };
})(jQuery);

El cambio se hace entonces:

var data = [{ id: 1, text: 'some value' }];
$('.js-some-field').refreshDataSelect2(data);

(El autor mostró originalmente var $select = $(this[1]);, que un comentarista corrigió a var $select = $(this[0]);, que muestro arriba.)

 0
Author: guero64,
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-27 20:24:47

Mi solución es:

$el.off('select2:unselect')
$el.on('select2:unselect', function (event) {
    var $option = $('<option value="" selected></option>');
    var $selected = $(event.target);

    $selected.find('option:selected')
             .remove()
             .end()
             .append($option)
             .trigger('change');
    });
 0
Author: Daniel Ortegón,
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-04 16:15:55
$('myselectdropdown').select2('val', '0')

Donde 0 es el primer valor del menú desplegable

 0
Author: Momaad Jamshed Alam,
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-09 10:14:23

Utilice este código en su archivo js

$('#id').val('1');
$('#id').trigger('change');
 0
Author: Nhoufy,
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-10 06:01:32

Para restablecer los valores y el marcador de posición simplemente reinicie el elemento select2:

$( "#select2element" ).select2({
    placeholder: '---placeholder---',
    allowClear: true,
    minimumResultsForSearch: 5,
    width:'100%'
});
 -1
Author: MeMeMax,
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-02-03 14:55:01