I have the following code:
<html>
<head>
</head>
<body>
<select name="" id="dia">
<script>
var d = new Date();
var selector = document.getElementById('dia');
for(var i = 1; i < 32; i++){
var toprint = "<option>"+i+"</option>";
document.write(toprint);
if(i==d.getDate()){
selector.selectedIndex = i
}
}
</script>
</select>
<select name="" id="mes"></select>
<select name="" id="anyo"></select>
</body>
</html>
The select element is filled by options as expected, but the index is not properly set. I've tried every component in separate, and I don't get why it isn't working.:
selector.selectedIndex
works when I use it in consolei
is obviously a valid number since it's iterating in the loop.- The
Javascript console
doesn't show any error or exception. So I assume there are no typos. - Placing an alert inside the
if
, it does work. So I assume the code is entering theif
clause. - I thought that maybe the index was being rewritten after every write, but I've tried placing
selectedIndex
outside the loop and it doesn't work either.
So... What am I missing?? I'm really out of ideas.
Your i goes from 1 to 31, but selectIndex starts at 0. So if the day is 15, you're trying to select index 15 which is item 16th actually and you haven't added it yet.
For example this code works:
Or, with minimum changes, your code can be rewritten as:
Please note that mixing JavaScript code with HTML is very bad practice and you should try to move away from this as you learn more.