Search code examples
drop-down-menuonloadselectedvalue

Setting the value of a dropdown list when a page loads


Hi and thanks for your help,

I am trying to set the value of a dropdown box when my page loads. Right now it gives me no errors, but the dang dropdown box isn't set to the value I wanted.

Here is my code:

<body onLoad="IssuesToReportForm.ReportTo.SelectedValue = '<%=strReportTo%>'">

Is this part of the code my problem?

Thanks, Will


Solution

  • <script type="text/javascript">
      function PreselectMyItem(itemToSelect)
      {
    
        // Get a reference to the drop-down
        var myDropdownList = document.IssuesToReportForm.ReportTo;
    
        // Loop through all the items
        for (iLoop = 0; iLoop< myDropdownList.options.length; iLoop++)
        {    
          if (myDropdownList.options[iLoop].value == itemToSelect)
          {
            // Item is found. Set its selected property, and exit the loop
            myDropdownList.options[iLoop].selected = true;
            break;
          }
        }
    
      }
    </script>
    

    Assuming IssuesToReportForm is your form name and your ReportTo dropdown's name.

    Then <body onLoad="PreselectMyItem('<%=strReportTo%>')">

    Source