When options won't change

Monday March 23, 2009

This weekend I had 6 new bugs opened against a website we are developing, and one of them really stumped me for a while. In short, we let the user edit some contents in an <input type="text" /> with an associated onchange-event that fires of some Javascript. The script updates a few other places on the page to reflect the new value, including a dropdown menu.

The strange thing was that it worked perfectly in most browsers, except Google Chrome and other Webkit based browsers. In short, the HTML for those dropdowns looks like this:

<select name="foobar">
  <option value="foo" label="Sometext">Sometext</option>
  <option value="bar" label="Somethingelse">Somethingelse </option>
</select>

Note the label-attribute on the <option>s. These were added by Smarty, which autogenerates that dropdown for us.

Naively, this was the code I had written:

<script type="text/javascript">
$('select option[value=foo]').text(newValue);
</script>

The HTML 4.01 spec has this to say about the label attribute:

This attribute allows authors to specify a shorter label for an option than the content of the OPTION element. When specified, user agents should use the value of this attribute rather than the content of the OPTION element as the option label.

So, since the label attribute should override the content of the <option> tag, this does not work in Webkit. Firefox, however, ignores this part of the spec.

So I ended up changing the code slightly to reflect that:

<script type="text/javascript">
$('select option[value=foo]').text(newValue).attr('label', newValue);
</script>

Works superbly.

Comments

Commenting is closed for this article.