JQuery Select2 - How to select all options

后端 未结 18 779
死守一世寂寞
死守一世寂寞 2020-12-02 10:50

I\'m using jQuery select2 multi select dropdown. I need to select all options in a dropdown from code. Basically there is a Select All checkbox on which this functionality h

18条回答
  •  一个人的身影
    2020-12-02 11:24

    This line of code will select all options

    $('select.select-all-class-name').attr('selected', true).parent().trigger('change');
    

    Add select events to work for all scenarios. The above line fails in a scenario, when you select and deselect an option and then click on selectAll. The last deselected option will not get selected. In order to fix that Add the below line of code.

    //Select options selected true for the selected option
    $('#mySelect2').on('select2:selecting', function (e) {
        $('select#mySelect2ID > option[value="'+e.params.args.data.id+'"]').attr('selected', true);
    });
    
    //DeSelect options selected to false for the option deselected
    $('#mySelect2').on('select2:unselecting', function (e) {
        $('select#mySelect2ID > option[value="'+e.params.args.data.id+'"]').attr('selected', false);
    });
    

提交回复
热议问题