Monday, April 30, 2012

Chrome not displaying Listbox selected item when used inside an Ajax UpdatePanel

On a page with an ASP.NET ListBox (HTML select with a "size" attribute) that is contained within an UpdatePanel Chrome isn't scrolling the select control to display the selected item when the update panel updates the page. The selection has been made, it just can't be seen if it isn't within the first items displayed.

Firefox and Internet Explorer scroll the select to display the selected item as expected both on the initial page load and the update panels partial page refresh.

I solved this by registering a call to a Javascript function in the PageRequestManager endRequest event (this fires after the update panel does the partial page refresh). The new Javascript function loops through the options on the select and toggles the selected attribute on the one that is currently selected.

 <script type="text/javascript">

  // For callbacks in webkit force the listBox to reselect.
  if ($.browser.safari) {
   var prm = Sys.WebForms.PageRequestManager.getInstance();
   prm.add_endRequest(function () {
    FocusSelected();
   });
  }

  function FocusSelected() {
   var lb = document.getElementById("<%= listBoxControlNameHere.ClientID %>");
   if (lb != null) {
    var options = lb.options;
    for (var i = options.length - 1; i > 0; i--) {
     if (options[i].selected == true) {

      var x = options[i];

      x.selected = false;
      x.focus();
      x.selected = true;

      return;
     }
    }
   }
  }
 </script>

See Also: