Reset selected option in a dynamically created select tag


I have noted a strange issue in Chrome with the select tag. I use code like the following to dynamically create options for a select tag (with jQuery):

var s = $('#selectid');
s.append('option 1');
s.append('option 2');
s.prop('selectedIndex', -1);

Note the last statement, I needed it to deselect the first option, most browsers will select it by default. With IE 9 the last statement works all right. It does not with Chrome. A workaround I saw implemented by another developer is to do the same in the onload event of an img tag, for instance:

<img alt="alt" src="img">

I am not a fan of event handlers and code mixed with HTML. The following is a modified version of the first code snippet that works with Chrome:

var s = $('#selectid');
s.append('option 1');
s.append('option 2');
setTimeout(function() {
  s.prop('selectedIndex', -1);
}, 100);

One side-effect of setTimeout is that the user may sometimes see the first option selected momentarily. Reducing the timer interval to let’s say 50 ms does not work. If you know of a better way to handle this, please leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s