简体   繁体   中英

How to remove unselected items of dropdownlist in javascript

I am looking for this question on internet since a while without success. I have a dropdownlist of some fruits. When an item is selected from the list, then the other items should be removed from the list. For example, if Apple is selected, then the other fruits should be removed and Apple only should stay in the list. => The function removeUnselectedOptions() does not perform consistently. here below the code:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Remove unselected items</title>
<script>
function removeUnselectedOptions() {
    var element = document.getElementById("fruitSelect");
    var length = element.length;
    var options = element.options;
    var selected = element.value;
    console.log(selected);
    console.log(length);
    var i = 0;
    do{
        console.log(i);
        console.log(options[i].value);
        console.log(selected);

        if(options[i].value != selected) {
            element.remove(i);
}
        i++;
   } while (i<length);
}
</script>
</head>

<body>
<form>

<br>
<select id="fruitSelect" size="5" onchange='removeUnselectedOptions();'>
    <option selected value="Select a fruit" >Select a fruit</option>
    <option>Apple</option>
    <option>Pear</option>
    <option>Banana</option>
    <option>Orange</option>
    </select>
    </form>
<br>
</body>
</html>

You can reduce your code to the following which gets the selected element's index, then loops backwards to remove it. Why backwards? Because if you loop forwards (like you'd normally do), the indexes change when you remove an element and it ends up leaving options as you probably noticed.

 function removeUnselectedOptions() { var element = document.getElementById("fruitSelect"); var selected = element.selectedIndex; for (var i = element.length-1; i >= 0; i--) { if (i != selected) element[i].remove() } } 
 <form> <br> <select id="fruitSelect" size="5" onchange='removeUnselectedOptions();'> <option selected value="Select a fruit">Select a fruit</option> <option>Apple</option> <option>Pear</option> <option>Banana</option> <option>Orange</option> </select> </form> 

other ways is :

function removeUnselectedOptions(){
    var element = document.getElementById("fruitSelect");
    var options = element.options;
    var i = 0;
    while (i < element.length){
        if(options[i].selected) {
            element.innerHTML = '<option value="'+options[i].label+'">'+
                options[i].label+
                '</option>';
            break;
        }
        i++;
    }
}

jsfiddle example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM