alfred jon alfred jon - 7 months ago 47
Javascript Question

Select2 - How to unselect all options and select only one

using

Select2
great plugin.

HTML:

<select id="fruits" multiple="true">
<option value=''>All
<option value='Apple'>Apple
<option value='Pear'>Pear
...


Javascript:

$('#fruits').select2();


When i select "All" option, I need to unselect all previously selected options and have only "All" option selected.

Tried
onChange="$('#fruits').select2('val', ['All']);"
as well as
onChange="$('#fruits').select2('data', ['All']);"


but it does not seems to work for me.

any clues?

Answer

here i the fiddle.. try this..

fiddle here

used click function ..

$(function() {
    $('#fruits').click(function(e) {
        var selected = $(e.target).val();
        if(selected=='all'){
           $('#fruits > option').prop("selected",false);
           $(e.target).prop("selected",true);
        };
    }); 
});