Selecting constraint item from list in asp.net using vb

I want to limit the number of select items from a list box in asp.net using vb. I tried to use javascript. But, it doesn't work. Help is needed

<asp:ListBox ID="lbprefferedlocation" runat="server" DataSourceID="locations" 
                DataTextField="City_Name" OnSelectedIndexChanged="chkCount(this)" DataValueField="City_Name" SelectionMode="Multiple"></asp:ListBox>
            <asp:HiddenField ID="hiddenChkCount" runat="server" />
            <asp:SqlDataSource ID="locations" runat="server" 
                ConnectionString="<%$ ConnectionStrings:JPConnString %>" 
                SelectCommand="SELECT [City_Name] FROM [State_Info]"></asp:SqlDataSource>



function chkCount(obj)
{
    if(obj.checked==true)
    {
        if( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value >= 5 )
        {
            alert('You cannot select more than 5 items.');
            obj.checked=false;
        }
        else
        {
            document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value ) + 1;
        }
    }
    else
    {
        document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value = parseInt( document.getElementById( '<%=hiddenChkCount.ClientID %>' ).value) - 1;
    }
}

      

+3


source to share


1 answer


You can use CustomValidator

:

 <asp:CustomValidator ID="CV_CheckLocationCount" runat="server"
     ValidateEmptyText="true" 
     ClientValidationFunction="CheckLocationCount"
     OnServerValidate="CheckLocationCount" 
     ControlToValidate="lbprefferedlocation"
     EnableClientScript="true" 
     ErrorMessage="Select at least one and at most 5 locations"
     ValidationGroup="VG_SAVE">*
</asp:CustomValidator>

function CheckLocationCount(sender, args){
    var count=$('#<%=lbprefferedlocation.ClientID %> option:selected').length;
    args.IsValid = count > 0 && count <= 5;
} 

      

Edit . And here's a solution without jQuery:



function validateListBoxSelectionCount(listbox, minSelected, maxSelected){
    var selected=0;
    if(listbox != null){
        for (var i=0; i<listbox.length; i++){
            if(listbox.options[i].selected){
               selected++; 
               if(selected>maxSelected)break;
            }
        }
    }
   return (selected >= minSelected && selected <= maxSelected);
} 

      

You can use it like this:

var listBox  = document.getElementById("<%=lbprefferedlocation.ClientID %>");
args.IsValid = validateListBoxSelectionCount(listBox, 1, 5);

      

+1


source







All Articles