Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - remove select option :selected attribute on click

Tags:

jquery

I'm working on a multiselect that pops up in a modal dialog. When the dialog closes, I'm populating a <ul> with <li>'s that contain text from the :selected options. When each individual <li> is clicked, I want the <li> to fade away and the corresponding :selected <option> to become unselected. I have everything working except unselecting the <option>.

Here's my code:

$('.control-finished').click(function(){
            $('ul.multiselect-dropdown-options-'+name+'').empty();
            $('option:selected', select).each(function(index, value) {
                var livalue = $(this).attr('value');
                $('ul.multiselect-dropdown-options-'+name+'').append('<li class="dropdown-option '+livalue+'">'+$(value).text()+'<!-- <a class="remove-option '+livalue+'"> -->x</li>');
                $('li.dropdown-option').click(function(){
                    $(this).fadeOut(500, function() { $(this).remove(); });
                    $('option:selected', this).removeAttr('selected');
                });
            });         

        });

Any help is greatly appreciated!

like image 454
Zumwalt Avatar asked Dec 09 '11 00:12

Zumwalt


People also ask

How remove selected attribute from select option in jquery?

With jQuery, you can use the . remove() method to takes elements out of the DOM. To get the selected item from a dropdown, you can use the :selected property and call remove() on the matched element.

How to remove the selected option in jQuery?

Select the option from select which needs to remove. Use JQuery remove() method to remove the option from the HTML document.

How to remove selected value from dropdown in jQuery?

How to remove one or more selected items in option tag, from a HTML dropdown list (Using Jquery). For removing entire options from a combo box we can use the below Jquery statement. $("#cmbTaxIds >option"). remove();


1 Answers

I believe your problem is on this line:

$('option:selected', this).removeAttr('selected');

This is saying, find all option:selected that is a descendent of li.dropdown-option. But you're deleting these after the fadeout, so of course it's not going to find it.

So you need to change the 2nd parameter in the jQuery function above. (this), to the actual parent dom element you wish to search under.

I don't know what your HTML looks like, so I can't provide you with a more detailed solution.

like image 124
Vigrond Avatar answered Sep 22 '22 10:09

Vigrond