I have this markup and javascript. I cannot get the "T" option (for example) to preselect on page load. Is it possible?
    <select id="serviceType" name="serviceType" class="form-control">
      <option value="S">S</option>
      <option value="T">T</option>
      <option value="X">X</option>
    </select>
    <script>
        //document.getElementById("serviceType").selectedIndex = "T"; // did not work
      var e = document.getElementById("serviceType");
      e.options[e.selectedIndex].value = "T"; // does not work
    </script>
Note: "T" is dynamic at page build time in PHP from a DB call. So my script actually looks like this:
= "<? echo $_POST['serviceType']; ?>"
Your commented out line did not work because the selectedIndex property of a select element expects an ordinal index of the element your wanted selected.    
document.getElementById("serviceType").selectedIndex = 1;
<select id="serviceType" name="serviceType" class="form-control">
  <option value="S">S</option>
  <option value="T">T</option>
  <option value="X">X</option>
</select>
If you want to set by the value then you can also set the value property of the element
document.getElementById("serviceType").value= "T";
<select id="serviceType" name="serviceType" class="form-control">
  <option value="S">S</option>
  <option value="T">T</option>
  <option value="X">X</option>
</select>
Just do it like this:
var e = document.getElementById("serviceType");
e.value="T";
Here is the working fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With