Careful when dealing with options in IE

14 April 2006   2 comments   Web development

Mind That Age!

This blog post is 12 years old! Most likely, its content is outdated. Especially if it's technical.

If you have a drop down that looks like this:

<select name="name"
 onchange="alert(this.options[this.selectedIndex].value)">
  <option>Bill</option>
  <option>Gates</option>
</select>

you'll get a different alert message in Firefox and IE6. Try it here

Firefox will understand that if you don't have a value attribute on a option tag, it takes the content of the option tag as the value. IE doesn't. On the above code it returns blank (aka. empty string) in the alert.

It's not been a problem until today for me but it's worth keeping in mind next time you need to read from a drop down with javascript. Ideally your javascript should do something like this:

var selectelement = document.forms[0].name;
var optionelements = selectelements.options;
var selected_option = optionelements[selectelement.selectedIndex];
var value;
if (selected_option.getAttribute('value')==null)
  value = selected_option.firstChild.nodeValue;
else
  value = selected_option.value;
alert(value);

...or something like that. But who can be asked? I just made sure my option tags always have a value attribute even though the XHTML 1.0 DTD does not require it.

Comments

Anonymous

Thanks mate!

Ebony

Slam duiknn like Shaquille O'Neal, if he wrote informative articles.

Your email will never ever be published


Related posts

Previous:
Case insensitive list remove call (part II) 11 April 2006
Next:
Date formatting in Python or in PostgreSQL (part II) 19 April 2006
Related by Keyword:
How to "onchange" in ReactJS 21 October 2015
An AngularJS directive with itself as the attribute 03 September 2014
OpenID, Attribute Exchange, SReg, python-openid and Google 23 April 2010
The importance of the TITLE attribute 23 April 2008
Better select boxes for issue tracker 29 April 2005
Related by Text:
jQuery and Highslide JS 08 January 2008
I'm back! Peterbe.com has been renewed 05 June 2005
Anti-McCain propaganda videos 12 August 2008
Ever wondered how much $87 Billion is? 04 November 2003
Guake, not Yakuake or Yeahconsole 23 January 2010