Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove selected options from multiple select box with Javascript Prototype?

I have searched quite a bit for the answer to this question, but no satisfactory result found.

I have this code:

<select name="items[]" size="0" id="feed-items-list" style="width:100%;" multiple="">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>

How do I remove all the selected options?

Thank you!

like image 445
stanki Avatar asked Mar 24 '23 05:03

stanki


2 Answers

I know you tagged prototypejs, but I've never used it before and it's easy enough with vanilla JS. Here's how to loop over the <option>s and see if they're selected or not:

var select_element = document.getElementById("feed-items-list");
var options = select_element.options;
var i = options.length;
while (i--) {
    var current = options[i];
    if (current.selected) {
        // Do something with the selected option
    }
}

DEMO: http://jsfiddle.net/tFhBb/

If you want to physically remove the option from the page, then use:

current.parentNode.removeChild(current);

If you want to unselect them, then use:

current.selected = false;
like image 75
Ian Avatar answered Apr 12 '23 14:04

Ian


To do this with PrototypeJS (as you tagged the question)

$('feed-items-list').select('option:selected').invoke('remove');

This will select elements with the CSS selector option:selected within the descendants of feed-items-list. Then invoke the specific method of remove on that element.

If you just want to unselect the option as Ian mentioned as well

$('feed-items-list').select('option:selected').each(function(i){
    i.selected = false;
});
like image 22
Geek Num 88 Avatar answered Apr 12 '23 14:04

Geek Num 88