Limit ASP.Net ListBox item selection using JavaScript and jQuery

Last Reply 10 months ago By dharmendr

Posted 10 months ago

Set the max number of items that can be selectable in ListBox in asp.net and c# using java scripts

<script type="text/javascript" language="javascript">
    function onClientSelectedIndexChangingHandler(source, arguments) {
        var listbox = document.getElementById('<%=ddlCOMMISION.ClientID%>');
        var selectedCount = 0;
        for (var index = 0; index < listbox.options.length; index++) {
            if (listbox.options[index].selected)
                selectedCount += 1;
        }
        if (selectedCount < 4)
            arguments.IsValid = true;
        else
            arguments.IsValid = false; 
    }
</script>
 
<asp:ListBox ID="ddlCOMMISION"  SelectionMode="Multiple" CausesValidation="True" Height="50px" runat="server">
    <asp:ListItem>--Select--</asp:ListItem>
    <asp:ListItem>% ON BASIC RATE</asp:ListItem>
    <asp:ListItem>% ON NETT ORDER AMT</asp:ListItem>
    <asp:ListItem>Rs PER KG</asp:ListItem>
</asp:ListBox>
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Maximum Countries you can select are 5"
    ClientValidationFunction="onClientSelectedIndexChangingHandler"></asp:CustomValidator>

 

Posted 10 months ago

Hi anirudhp,

Refer the below code.

HTML

<asp:ListBox ID="ddlCOMMISION" SelectionMode="Multiple" CausesValidation="True" Height="50px"
    runat="server">
    <asp:ListItem>% ON BASIC RATE</asp:ListItem>
    <asp:ListItem>% ON NETT ORDER AMT</asp:ListItem>
    <asp:ListItem>Rs PER KG</asp:ListItem>
</asp:ListBox>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('[id*=ddlCOMMISION]').on('change', function () {
            var selectedCount = 0;
            $('[id*=ddlCOMMISION] option').each(function () {
                if ($(this).is(':selected')) {
                    selectedCount++;
                }
                if (selectedCount > 2) {
                    alert("you can select max 2 of items");
                    $(this).removeAttr("selected");
                }
            });
        });
    });
</script>

Screenshot