Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For is only getting odd numbers

Tags:

javascript

So I have this code that deletes options from a select (0-23) but it's only deleting 0 and odd numbers. The options that remain are 2, 6 , 10, 14, 18, 22. The goal is to delete all options in the for Code:

var x = 0; 
var select = document.getElementById("hour");
var length = select.options.length;
for (x = 0; x < length; x++) {
    select.options[x] = null;
};
like image 486
Miguel Leal Avatar asked Jan 26 '26 03:01

Miguel Leal


1 Answers

Try looping reversed

var select = document.getElementById("hour");
var length = select.options.length;
for (var x = length-1; x >= 0; x--) {
    select.options[x] = null;
};

Also you may use remove method instead setting it to null value

select.remove(x);

Issue with your code is, when you remove 0th index option then first one comes at 0th index resulting next iteration to delete 1st index instead current first.

like image 114
Bilal Siddiqui Avatar answered Jan 27 '26 18:01

Bilal Siddiqui



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!