Thursday, January 25, 2007

IE6 SELECT value gotcha

Consider the following HTML and JavaScript snippet, which attempts to grab the selected value of a SELECT element:

<select name="city" id="citySelector">
  <option selected="true">Tacoma</option>
var s = document.getElementById("citySelector");
var v = s.options[s.selectedIndex].value;

In Firefox the result will be the string of selected city ("Tacoma"). IE6 however will return a blank string. Why?

Look at the HTML. None of the options have a value attribute. This is pretty common in markup where the option text is the same as the value. When used with a form POST or GET, most browsers send the option text in lieu of the missing value attribute.

But when accessing the value from JavaScript, Firefox plays fast and loose, whereas IE6 is stricter, returning nothing for the value because none was explicity given.

Here's a solution that works in both browsers:

var v = s.options[s.selectedIndex].text;