Zeyukan Ich'
Zeyukan Ich'

Reputation: 693

Allow duplicates selection in select2 dropdown

I would like to allow multiple select of a same value as shown here : https://jsfiddle.net/DinoMyte/qcgvucnz/1/ (tried with select2-3.5) but I'm with select2-4.0. Since I'm using Laravel Voyager, I can't change the version.

Currently, the multi-select is working as in here : https://select2.org/getting-started/basic-usage

I don't really know how to achieve that and I already went to all the github to find some solution with no result

I tried some things on this event specifically : but it did nothing

        $(this).on('select2:select',function(e){
            var data = e.params.data;
            $(e.currentTarget).find("option[value='" + data.id + "']").attr('selected','selected');;
        });

Did someone already achieve that?

Upvotes: 0

Views: 1833

Answers (1)

Rijento
Rijento

Reputation: 41

I managed to figure this out the other day.

$(this).on('select2:unselect', function (e) {
    //console.log("UNSELECT");
    //console.log(e);
    if (e.params.originalEvent != null && e.params.originalEvent.handleObj.type == "mouseup") {
        $(this).append('<option value="' + e.params.data.id + '">' + e.params.data.text + '</option>');
        let vals = $(this).val();
        vals.push(e.params.data.id);
        $(this).val(vals).trigger('change');
        $(this).select2('close');
    } else if (e.params.data.element != null) {
        e.params.data.element.remove();
    }
});

I found that (in Select2 4.1.0) when you re-select a value it calls the 'unselect' event instead of the 'select' event. Additionally, the trigger for that event is always 'mouseup' when selecting in this manner and 'click' when you actually click the button to remove the selected object.

You need to add the option to the select element and then tell Select2 to pick that value (again) and trigger a change event.

You can take it one step further if you want maximum efficiency by using the 'unselecting' event as well.

$(this).on("select2:unselecting", function (e) {
    //console.log("PREUNSELECT");
    //console.log(e);
    if (e.params.args.originalEvent != null && e.params.args.originalEvent.handleObj.type == "mouseup") {
        $(this).append('<option value="' + e.params.args.data.id + '">' + e.params.args.data.text + '</option>');
        let vals = $(this).val();
        vals.push(e.params.args.data.id);
        $(this).val(vals).trigger('change');
        $(this).select2('close');
        e.preventDefault();
    }
})
$(this).on('select2:unselect', function (e) {
    //console.log("UNSELECT");
    //console.log(e);
    if (e.params.data.element != null) {
        e.params.data.element.remove();
    }
});

Upvotes: 2

Related Questions