Select a Dropdown List Item Using JavaScript

The following JavaScript functions are useful for selecting items in HTML dropdown lists. These can be used especially if you have server-side code returning values that should then be visually selected on the user’s screen without rebuilding the entire page.

<select id="country_list" name="country_list">
  <option value="1">USA</option>
  <option value="2">Canada</option>
  <option value="3">Mexico</option>
</select>

This first function will select an item based on its value. Pass in an object referring to a list element, e.g. document.getElementById(“country_list”), and the value that should be selected.

  function selectItemValue(list, selectedValue) {
    for(j = 0; j < list.options.length; j++) {
      if(toUpper(list.options[j].value) == toUpper(selectedValue)) {
        list.selectedIndex = j;
        break ;
      }
    }
  }

This second function will select an item based on its displayed text name. Pass in an object referring to a list element, e.g. document.getElementById(“country_list”), and the displayed text value that should be selected.

  function selectItemText(list, selectedText) {
    for(j = 0; j < list.options.length; j++) {
      if(toUpper(list.options[j].text) == toUpper(selectedText)) {
        list.selectedIndex = j;
        break ;
      }
    }
  }

The following is an example of how to call both functions:

selectItemValue(document.getElementById("country_list"), 1);
selectItemText(document.getElementById("country_list"), "USA");

About John Dalesandro

My name is John Dalesandro and I am a software engineer based in New Jersey. My experience covers all aspects of the software development life cycle with a primary focus on enterprise web applications.