Disable the unselected options of multiselect with jquery

Asked

Viewed 53 times

0

$('#columns-selected').change(function(){

    let menu = [];

    for (i=0; i < 5; i++){
        let opcao = $('#columns-selected option:selected')[i]; 
  
        if (opcao){
            menu.push($(opcao).val());
        };
    }

    $.ajax({
      method: 'POST',
      url: base_url+'fornecedor/menuPadrao/',
      dataType: 'JSON',
      data: { menu: menu },
      success: function(data)
       {
         if(!data.result == true){
           alert('Ocorreu um erro tente novamente!');
         }
       }
      
    });
})
1 - Today in select I can select several but it only takes the first 5 selected and send via ajax to the controller as shown in the code above.

Doubt/Question/Suggestion

How would you make it so that when the user selects 5, in addition to sending the 5 via ajax, disable the rest of the options in select ???

1 answer

0


Take the test there bro! I believe it solves your problem.

$('#columns-selected').change(function(){

//FAZ A CONTAGEM DE OPÇÕES MARCADAS NO SELECT
var selectedOptions = $("#columns-selected :selected").length;
if(selectedOptions == 5)
{
    ///ARRAY COM OS SELECIONADOS...
    var menu = $(this).val();
    ///DESABILITA AS OPÇÕES QUE NÃO FORAM MARCADAS...
    $("#columns-selected option:not(:selected)").attr('disabled','disabled');

    //ENVIA OS DADOS DO SELECT...
    $.ajax({
        method: 'POST',
        url: base_url+'fornecedor/menuPadrao/',
        dataType: 'JSON',
        data: { menu: menu },
        success: function(data) 
        {
            if(!data.result == true){
                alert('Ocorreu um erro tente novamente!');
            }
        }
    }); 

}
else if(selectedOptions > 5)
{
    //SE MARCAR MAIS DE 5 OOÇÕES DE UMA VEZ (ex:USANDO A TECLA SHIFT), DESMARCA TUDO.
    $("#columns-selected").val([]);

} else if(selectedOptions < 5) {
    ///SE DESMARCAR UMA DAS OPÇÕES, LIBERA TODAS AS OPÇÕES DO SELECT DE NOVO;
    $("#columns-selected option:not(:selected)").removeAttr("disabled");
}

})

  • @Visiondevelopment had not seen that you wanted to disable only those that were not marked, if that’s what it is, I updated the code accordingly. if it helps you bro, please mark the answer as correct.vlw.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.