Zumwalt
Zumwalt

Reputation: 151

jQuery - if select option is unselected, remove an element

I'm working on a multiselect that creates an <li> using the text of each :selected option. How would I go about removing that <li> if the option becomes unselected?

I'm using the code below (from here) to append the <li> for each :selected item.

    $('option:selected', select).each(function(index, value) {
            $('ul.multiselect-dropdown-options-'+name+'').append('<li>'+$(value).text()+'</li>');
        });

Upvotes: 0

Views: 1062

Answers (1)

David Thomas
David Thomas

Reputation: 253308

I've adapted your code to the following:

$('#select').change(
    function(){
        $('#ulSelect').empty();
        $(this).find('option:selected').each(
            function(){
                $('<li />').text($(this).text()).attr('data-value',this.value).appendTo($('#ulSelect'));
            });
    });

JS Fiddle demo

This takes care of the de-selection by, each time the select changes, emptying the ul and then appending only those elements that are selected into the ul.

The li elements are, however, given a data-* attribute containing a reference to the original value of the option from which they were taken/copied, so it should be possible to relate the li to the original option should you want to take a different approach.

References:

Upvotes: 1

Related Questions