Search code examples
javascriptselectedindex

Why isn't selectedIndex working in this code?


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 console
  • i 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 the if 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.


Solution

  • 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:

      <select name="" id="dia">
        <script>
          var d = new Date();
    
          for (var i = 1; i < 32; i++) {
            var toprint = "<option>" + i + "</option>";
            document.write(toprint);
          }
    
          var selector = document.getElementById('dia');
          selector.selectedIndex = d.getDate() - 1
        </script>
      </select>
      <select name="" id="mes"></select>
      <select name="" id="anyo"></select>
    

    Or, with minimum changes, your code can be rewritten as:

      <select name="" id="dia">
        <script>
          var d = new Date();
          var selector = document.getElementById('dia');
    
          for (var i = 0; i < 31; i++) {
            var day = i + 1;
            var toprint = "<option>" + day + "</option>";
            document.write(toprint);
            if (day == d.getDate()) {
              selector.selectedIndex = i
            }
          }
        </script>
      </select>
      <select name="" id="mes"></select>
      <select name="" id="anyo"></select>
    

    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.