Koks_rs
Koks_rs

Reputation: 680

select2:unselect doesn't work properly

I have a problem with Select2, when I click on the cross sign with mouse (please note: allowClear is true) select2:unselect event is fired but the chosen before value remains chosen for some time.

<select id='select2'>
<option value='1'>option 1</option>
</select>

$("#select2").select2({
    placeholder: "placeholder",
    dropdownAutoWidth: true,
    allowClear: true
})


$("#select2").on("select2:select select2:unselect", function (e) {

    var currentValue = $(this).val(); 

    console.log($(this).val());
    setTimeout(function () {
        console.log($("#select2").val());
    }, 2000)

});

I need to get current value, if nothing selected I would expect null.

Is there a correct way to get the current select2 value?

Here is the demo - jsfiddle

Upvotes: 1

Views: 2011

Answers (1)

Vitaly
Vitaly

Reputation: 1281

Try this:

$("#select2").on("change", function (e) {

    var currentValue = $(this).val();  // I want null when unselect is fired

    console.log($(this).val());
    setTimeout(function () {
        console.log($("#select2").val());
    }, 2000)

}); 

Upvotes: 1

Related Questions