Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select option remove() method on removing multiple options

Tags:

javascript

I'm having a select box which contains 17 values/options.

<select id="_class" name="_class">
    <option value="0"></option>
    <option value="1">PREKG</option>
    <option value="2">LKG</option>
    <option value="3">UKG</option>
    <option value="4">I</option>
    <option value="5">II</option>
    <option value="6">III</option>
    <option value="7">IV</option>
    <option value="8">V</option>
    <option value="9">VI</option>
    <option value="10">VII</option>
    <option value="11">VIII</option>
    <option value="12">IX</option>
    <option value="13">X</option>
    <option value="14">XI</option>
    <option value="15">XII</option>
    <option value="16">XIII</option>                              
</select>

Now, I'm trying to remove the option from 5 to 8. For that, I'm using the following JavaScript code.

<script type="text/javascript">
 var _class = document.getElementById("_class");
 for(var i=1; i < _class.length;i++) {
   if(i>=5 && i<=8) {
     _class.remove(i);
   }
 }
</script>

But, I'm not getting the expected result, because every time as if the for loop runs, the order of the option is getting changed.

How can I get the desired result?

Here I've attached the Fiddle.

like image 553
Vijin Paulraj Avatar asked Sep 16 '26 11:09

Vijin Paulraj


1 Answers

By iterating through the options incrementally, the indices of the options after an option that is removed will be reduced by one as soon as the option is removed (ie: removing the option at index 5 causes options 6 and above to now be indexed as options 5 and above).

To cater for this, reverse the order of the loop to count downwards:

var _class = document.getElementById("_class");

for(var i=Math.min(_class.options.length, 8); i >= 5; i--) {
  _class.remove(i);
}

http://jsfiddle.net/Gy8j8/2/

like image 173
steveukx Avatar answered Sep 19 '26 02:09

steveukx



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!