Friday, May 29, 2009

JQuery, IE6, and 'Could not set the selected property. Unspecified error.'

I was trying to do this with JQuery - imagine htmlOptions is a client-side cache of option values to put in a select box, ctrl is the id of the box, and id is the current selected value:


function loadDropDown(htmlOptions, ctrl, id) {
   $(ctrl).html(htmlOptions); 
   $(ctrl).val(id); 
}

It worked great on everything but IE 6.0. Then I got the big, fat "Could not set the selected property. Unspecified error." Turns out there is a little bit of a timing issue with the DOM. After scouring the 'net for solutions, I finally settled on this as my favorite - no crazy browser hacks to determine the type and version, IE 6.0 gets the short end of the stick as it deserves:


function loadDropDown(htmlOptions, ctrl, id) {
   $(ctrl).html(htmlOptions); 
   try {
      $(ctrl).val(id); 
   }
   catch(ex) {
      setTimeout("$('" + ctrl + "').val('" + id + "')",1); 
   }
}

It's just enough delay to let the DOM settle and not complain.

Jeremy Likness