Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide (NOT remove) option in select2?

Is it possible to hide the option from select2 without removing it?

My current code only disables the option:

$('#company_id').change(function () {
    var company_name =  $("#company_id option:selected").text();
    var $owner_id = $("#owner_id");

    $owner_id.select2("destroy"); 

    $("#owner_id option:not(:contains('(" + company_name + ")'))")  
        .prop('disabled',true);

    $("#owner_id option:contains('(" + company_name + ")')")
        .prop('disabled',false);

    $owner_id.select2();
});
like image 516
belov91 Avatar asked Dec 07 '25 01:12

belov91


1 Answers

You can comment HTML code with jQuery, your code will look something like this:

$('#company_id').change(function () {
    var company_name =  $("#company_id option:selected").text();
    var $owner_id = $("#owner_id");

    $owner_id.select2("destroy"); 

    //Comment element
    element = $("#owner_id option:not(:contains('(" + company_name + ")'))");
    comment = document.createComment(element.get(0).outerHTML);
    element.replaceWith(comment);

    //Unomment element
    $("#owner_id option:contains('(" + company_name + ")')").replaceWith(comment.nodeValue);

    $owner_id.select2();
});

If not works try to do it inside a loop for each element to comment or uncomment, I will try it later.

like image 157
campsjos Avatar answered Dec 08 '25 13:12

campsjos