If I try to remove all the options with the following code from a multiple select box, not all options will be removed.
What do I wrong?
var e = document.getElementById("category2").options;
for (var i = 0; i < e.length; i++) {
e[i].remove();
}
<select id="category2" name="category_id[]" multiple="multiple" size="10">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
4
Answers
The issue is that every time you run
.remove()
,e.length
gets decremented by one, buti
stays just as high, so eventually it will be less thani
.To fix this, just create a copy of
e.length
(so it doesn’t change) and removee[0]
each time. If you keep removinge[i]
, theni
will be larger thane.length
and the element won’t exist:Maybe a little faster and simpler:
looking for this ?
in your question you have 1 selectbox and your answer is this:
if you have multiple selectbox, you can use this
or use function