How to disable options in select2

10,917

you can reinitialize select after disabling it use following code

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

something like

$('select[name*="pref"]').change(function(){

    // start by setting everything to enabled
    $('select[name*="pref"] option').prop('disabled',false);

    // loop each select and set the selected value to disabled in all other selects
    $('select[name*="pref"]').each(function(){ 
        var $this = $(this);
        $('select[name*="pref"]').not($this).find('option').each(function(){
           if($(this).attr('value') == $this.val()){            
               $(this).prop('disabled',true);               
           }
        });
    });
    $('select[name*="pref"]').select2("destroy").select2();
});

hope i am getting you right

Share:
10,917
Vamshi
Author by

Vamshi

Love coding.

Updated on July 14, 2022

Comments

  • Vamshi
    Vamshi almost 2 years

    I want to take user's preference with select2. Upon selecting one option the option in other select2 should disable.

    Sample:

    Preference 1: Option 1 Option 2 Option 3 Option 4

    Preference 2: Option 1 Option 2 Option 3 Option 4

    Preference 3: Option 1 Option 2 Option 3 Option 4

    Preference 4: Option 1 Option 2 Option 3 Option 4

    If I select option 1 in preference 1 it should disable in preferences 1,2,3,4 and if I select option 2 in preference 2 it should disable in preferences 1,2,3,4 and if I select option 3 in preference 3 it should disable in preferences 1,2,3,4

    Again and if I select option 4 in preference 2 it should disable in preferences 1,2,3,4 and option 2 should be available for select in Preferences 3&4.

    I have tired various implementations but stuck. Help me out.

    HTML:

    <div class="form-group col-md-6 m-t-sm">
        <label> Select Preference 1: </label>
        <select class="form-control" id="pref1" name="pref1" style="width:100%">
        <option value=""> Select Campus Preference 1 </option>
        <option value="N"> N </option>
        <option value="O"> O </option>
        <option value="R"> R </option>
        <option value="S"> S </option>
        </select>
        <label id="pref1-error" class="error" for="pref1"></label>
    </div>
    .
    .
    .
    

    My current js:

    $('select[name*="pref"]').change(function(){
    
        // start by setting everything to enabled
        $('select[name*="pref"] option').prop('disabled',false);
    
        // loop each select and set the selected value to disabled in all other selects
        $('select[name*="pref"]').each(function(){ 
            var $this = $(this);
            $('select[name*="pref"]').not($this).find('option').each(function(){
               if($(this).attr('value') == $this.val()){            
                   $(this).prop('disabled',true);               
               }
            });
        });
    
    });