Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clear html select option group

Tags:

javascript

I know you can clear options by doing the following:

dropDownList.options.length = 0;

Is there a way to clear option groups? Seems like the only way is to remove nodes one at a time.

like image 251
makstaks Avatar asked Nov 24 '25 12:11

makstaks


1 Answers

Try getting ahold of the optgroup element and then remove it from the DOM:

<body>
<select id="mySelect" onchange="npup(this);">
    <optgroup label="Foo" id="foo_group">
        <option value="foo0">foo0</option>
        <option value="foo1">foo1</option>
    </optgroup>
    <optgroup label="Bar" id="bar_group">
        <option value="bar0">bar0</option>
        <option value="bar1">bar1</option>
    </optgroup>
    <option value="kill_foo">Remove foo</option>
</select>

<script type="text/javascript">

function npup(selectElem) {
    // get value and check it
    var value = selectElem.value, foo;
    if (value==='kill_foo') {
        // retrieve optgroup
        foo = document.getElementById('foo_group');
        // remove the group from its parent
        foo.parentNode.removeChild(foo);
    }
}
</script>
</body>
like image 180
npup Avatar answered Nov 26 '25 00:11

npup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!