Search code examples
jqueryjquery-select2jquery-select2-4

select2, how to change before show


I'm using select2 to build my combo.

some elements are disabled, but I want to show them bold but with aria-required="false"

var data= [{
     id="1",
     value = "first",
     disabled:true
},{
     id="2",
     value = "second",
     disabled:false
},

];
function formatResult(node) {
  if(node.disabled){
    var $result = $('<span><strong>' + node.text + '</strong></span>');
  } else {
    var $result = $('<span>' + node.text + '</span>');
  }
  return $result;
}

$("#myCombo").select2({
  placeholder: 'Seleccione una opción',
  width: "350px",
  data: data,
  formatSelection: function(item) {
    return item.text
  },
  formatResult: function(item) {
    return item.text
  },
  templateResult: formatResult
});

};

that works, but the li :

<li class="select2-results__option" role="treeitem" aria-disabled="true">
        <span style="padding-left:20px;"><strong>first</strong></span>
</li>

when it's opened, with debugger, if I execute:

$('.select2-results__option').attr('aria-disabled',false);

it works as I want, but I'm not able to do this programatically, it seems there is not exists a beforeShow function, how can I do this?


Solution

  • Generally, you can achieve this with a timeout.

    $("#myCombo").select2({
      placeholder: 'Seleccione una opción',
      width: "350px",
      data: data,
      formatSelection: function(item) {
        return item.text
      },
      formatResult: function(item) {
        return item.text
      },
      templateResult: formatResult
    });
    setTimeout(function(){
      $('.select2-results__option').attr('aria-disabled',false);
    });