Select2 auto change trigger event

I have 4 select boxes, when I change the first one, do something like empty, add and set a new value for the next one.

Since I'm using select2, I can just set it with $ .select2 ('val', 'value');

Only this command fires a change event on another select and makes a cascade of changes.

Note that .empty () and append () do not fire the trigger (and I like that), even .val () should not fire it, but when ure is using select2, you cannot access the new val using that.

The code is here:

function anidado(selectorOrigen,selectorDestino) {
  id = selectorOrigen;
  alert(id);
  destino = "#"+selectorDestino;
  valor = $('#'+id).find(":selected").val();
  $.ajax({
    method: "GET",
    url: "blanco2.php",
    data: { select: id, valor: valor }
  })
  .done(function( msg ) {
      obj = $.parseJSON( msg );
      if (obj.length>0) {
        $(destino).empty().append('<option value="x">Select an ---</option>').select2("val", "x");
        $.each(obj,function(index) {
          valor = obj[index].codigo;
          texto = obj[index].descripcion;
          $(destino).append('<option value=' + valor + '>' + texto + '</option>');
          $(destino).prop("readonly",false);

        });
      } else {
        $(destino).empty().append('<option value=""></option>').select2("val", "");
      }

  });
  return false;
}

$( "select" ).change(function() {
  selectorOrigen = this.id;
  if (selectorOrigen === 'pais') {
    selectorDestino = 'ua';
  } else if (selectorOrigen === 'ua') {
    selectorDestino = 'unidad';
  } else if (selectorOrigen === 'unidad') {
    selectorDestino = 'rol';
  } else if (selectorOrigen === 'rol') {
    selectorDestino = 'categoria';
  } else { return false; }
  anidado(selectorOrigen,selectorDestino);
});

      

It was pretty, but it didn't work for me Clear select2 without triggering change event

He suggests using something like

$docInput.select2('data', null, false);

      

I just need to set the new selected option without triggering a change event. Any alternative to .select2 ("val", "x") when using the select2 plugin?

+3


source to share


1 answer


select2 4.0 requires the standard .val () base element attribute to be called when the value changes. Details on this can be seen at the bottom of the select 4.0 announcement https://select2.github.io/announcements-4.0.html .

To select the value you should use:

//Select value without triggering change event
$(destino).val('x');

//Select value and trigger change event
$(destino).val("x").trigger("change")

      



Note that due to the parameters being added, you must initialize select2 first to make sure the value is selected. i.e.

//Re-initialize and set value without triggering change event
$(destino).select2();
$(destino).val('x');

      

Take a look at the following fiddle for a working example https://jsfiddle.net/wfkxdjr6/ .

+14


source







All Articles