<$BlogRSDUrl$>

Friday, October 22, 2004

Scrolling a multiple select list 

Sometimes something that seems so simple can turn out to be unbelievably difficult. One such problem that I resently ran into is the problem of scrolling an HTML select control to the last selected item after an ASP.NET postback. Normally if you select an item that is below the visible number of lines, if the list is in single select mode the control will automatically scroll to make the selected item visible. If the list is in multiple select mode, the list will not scroll and the fact that there are selections below the visible lines will not be known.

The key to solving this problem is to write javascript that reselects the last selected entry and then schedules this javascript to run after a few miliseconds. There is no javascript scroll command, and this fix will not work without the delayed asych execution. I have changed the script tag to 'scrpt' in order to overcome security checks on embedded javascript.

    Private Sub Page_PreRender(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.PreRender
        'build string to set the focus on the current control
        Dim sFocus As String
        If Not focusControl Is Nothing Then
            sFocus = String.Format( _
            "try{{document.getElementById('{0}').focus();}}catch(x){{}}", _
             focusControl.ClientID)
        End If

        'build a string that will autoscroll the list boxes if they have selection that are not visible by default
        Dim sb As New System.Text.StringBuilder

        sb.Append("")
        sb.Append("function AutoScroll(){")
        sb.Append(sFocus)
        sb.Append(" var f = document.forms[0];")
        sb.Append("for (var num=0; num < ")
        sb.Append("f.elements.length;num++)")
        sb.Append("{")
        sb.Append("if (f.elements[num].type.indexOf('select')==0)")
        sb.Append("{")
        sb.Append("var si = f.elements[num].selectedIndex;")
        sb.Append("if (si >= 0) ")
        sb.Append("{")
        sb.Append("var maxi = f.elements[num].selectedIndex;")
        sb.Append("for (var i=maxi; i < ")
        sb.Append("f.elements[num].options.length;i++){")
        sb.Append("if(f.elements[num].options[i].selected){maxi=i}")
        sb.Append("}")
        sb.Append("var ooo = f.elements[num].options[maxi]; ")
        sb.Append("ooo.selected=true;")
        sb.Append("}")
        sb.Append("}")
        sb.Append("}")
        sb.Append("}")
        sb.Append("")

        sb.Append(" ")
        sb.Append("window.setTimeout(""AutoScroll()"",5)")
        sb.Append("")

        Page.RegisterStartupScript("radchk", sb.ToString)

    End Sub

Topics: ASP.NET | Javascript


Links to this post:

<\$BlogItemBacklinkCreate\$>

Comments: Post a Comment

This page is powered by Blogger. Isn't yours?