Search code examples
jquery-select2-4

How do I clear dataitems from select2


I would like to refill the options of my select2, the old options should not be available only the new ones. I have a select2 that is filled with the following data:

$('select')
    .select2({
    data: [{
        id: 'Spock',
        text: 'Spock'
    }, {
        id: 'Kirk',
        text: 'Kirk'
    }]
})

Now I would like to replace the option with StarWars alternatives like this:

$('select')
    .select2({
    data: [{
        id: 'Luke',
        text: 'Luke'
    }, {
        id: 'Darth',
        text: 'Darth'
    }]
})

The result when after both scripts are run, is a select2 that contains both StarTrek and StarWars dudes. How do I remove the old items? Here is a JsFiddle with the example above.


Solution

  • You need to remove the previous options of select box before replacing the StarWars alternatives using $('select').html('');. So your code would be like this:

    $('select')
        .select2({
        data: [{
            id: 'Spock',
            text: 'Spock'
        }, {
            id: 'Kirk',
            text: 'Kirk'
        }]
    });
    
    $('select').html('');   // use this to remove previous options
    
    $('select')
        .select2({
        data: [{
            id: 'Luke',
            text: 'Luke'
        }, {
            id: 'Darth',
            text: 'Darth'
        }]
    });
    

    See this fiddle for more details.