Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preselect a <select> list item in using JavaScript

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']; ?>"

like image 728
H. Ferrence Avatar asked Dec 15 '22 10:12

H. Ferrence


2 Answers

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>
like image 70
Jamiec Avatar answered Dec 17 '22 02:12

Jamiec


Just do it like this:

var e = document.getElementById("serviceType");
e.value="T";

Here is the working fiddle.

like image 28
Deepak Biswal Avatar answered Dec 17 '22 00:12

Deepak Biswal