• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 997
  • Last Modified:

asp.net multiple select or select all control

In asp.net 4, I would like to implement a web control using dropdown or listbox. User is able to select All or make a multiple selections from that control. For example: List items are:

0--All
1--Month 1
2--Month 2
3--Month 3
...
11--Month 11
12--Month 12

If select 'All' then disable other selections on Month 1-12
If unselect "All" then enable Month 1-12 multiple selections
If select any Month, disable "select All"
As well would like to display what are selected.  Checkbox list in (dropdown or listbox) both are fine. Very appreciated if you could provide the code to implement this.
Thanks,
0
shirleyz8821
Asked:
shirleyz8821
  • 4
  • 4
2 Solutions
 
Steve KrileCommented:
Sounds like you are really talking about client-side behavior, not server-side logic.  Before I show an example of how to get this done, are you comfortable with jquery?
0
 
shirleyz8821Author Commented:
No, I am not comfortable jquery, but comfortable with javascript,c# and asp.net
0
 
Steve KrileCommented:
I think you will like jQuery.  If you understand javascript you will certainly be able to get your head around it.  jQuery is really just a giant helper class for the most common javascript activities.  For instance, DOM selection, event wiring, animations, etc.

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="content-type" content="text/html" />
<meta name="author" content="Evan Cutler" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<title>Untitled 2</title>
    
    <style type="text/css">
        body {font-family:Arial;}
        #text {border:solid 2px gray;background:#ffc;padding:4px;width:250px;}
    </style>
    <script type="text/javascript">

        //wait until the DOM has finished loading all of the HTML elements before binding the CHANGE event to all the check boxes
        $(document).ready(function () {

            //in jQuery you can select multiple DOM elements with a single command
            //in this example, I'm telling jQuery to find all INPUT elements that have a type of CheckBox
            //then, using jQuery's chaining capability I'm telling it to take each of those checkboxes and bind a CHANGE event to each one.
            //the function for that change event is what starts on the next line
            $("input[type=checkbox]").change(function () {
                //get the value of the checkbox
                //$(this)  is the jQuery way of selecting the .change() object that was changed
                //or - the clicked item in this case
                var checkbox = $(this);

                var val = checkbox.val();

                //determine if it is checked
                var isChecked = checkbox.attr("checked");

                //if the CHECK ALL box is being clicked
                if (val == 0) {
                    //if the box was turned on
                    if (isChecked) {
                        //select all the check boxes that are not this checkbox
                        $("input[type=checkbox]").not($(this))

                        //then loop through each one and remove the checked designation and disable them
                        .each(function () {
                            $(this).removeAttr("checked");
                            $(this).attr("disabled", true);
                        })
                    }
                    else {
                        //select all the check boxes that are not this checkbox
                        $("input[type=checkbox]").not($(this))

                        //then loop through each one enable them
                        .each(function () {
                            $(this).removeAttr("disabled");
                        })

                    }
                }

                //this is just to help you see what is happening when you click.
                $("#text").text("You just click on value: " + val + " and the box is " + ((isChecked) ? "" : "NOT") + " checked.")
            });
        });
    </script>
    
</head>

<body>
    <ul>
        <li><label for="month_0">ALL</label><input type="checkbox" id="month_0" value="0" class="checkALL" /></li>
        <li><label for="month_1">Month 1</label><input type="checkbox" id="month_1"  value="1" /></li>
        <li><label for="month_2">Month 2</label><input type="checkbox" id="month_2"  value="2" /></li>
        <li><label for="month_3">Month 3</label><input type="checkbox" id="month_3"  value="3" /></li>
        <li><label for="month_4">Month 4</label><input type="checkbox" id="month_4"  value="4" /></li>
        <li><label for="month_5">Month 5</label><input type="checkbox" id="month_5"  value="5" /></li>
        <li><label for="month_6">Month 6</label><input type="checkbox" id="month_6"  value="6" /></li>
        <li><label for="month_7">Month 7</label><input type="checkbox" id="month_7"  value="7" /></li>
        <li><label for="month_8">Month 8</label><input type="checkbox" id="month_8"  value="8" /></li>
        <li><label for="month_9">Month 9</label><input type="checkbox" id="month_9"  value="9" /></li>
        <li><label for="month_10">Month 10</label><input type="checkbox" id="month_10"  value="10" /></li>
        <li><label for="month_11">Month 11</label><input type="checkbox" id="month_11"  value="11" /></li>
        <li><label for="month_11">Month 12</label><input type="checkbox" id="month_12"  value="12" /></li>
    </ul>
    <div id="text"></div>
</body>
</html>

Open in new window


I've also thrown together a Fiddle for this:

http://jsfiddle.net/skrile/UXgAZ/
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
shirleyz8821Author Commented:
Thanks Skrile for your code. But I unable to link to http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js because it was blocked by IE8 security configuration. I like the code feature but I unable to run it. Can you please convert the Jquery to javascript? Very appreciated with your help. Thanks!
0
 
Steve KrileCommented:
Jquery code *is* javascript - just leveraging a library of helpers.  If external links to the jquery library do not work, you should download the library and change my example to reference the file locally.  The file in total is less than 100k and allows for far more elegant code writing.

In short, no - and it's quite likely I'd mess it up anyway.  I haven't written straight javascript code in a long time.
0
 
Robert SchuttSoftware EngineerCommented:
First off, @skrile: your solution does look elegant, and the fully commented code deserves every credit.

@shirleyz8821, I have an alternative 'at the other end of the spectrum' because I'm not sure if you can only use a client-side solution. By the way I'm quite sure it can be done in pure javascript but without a library/framework like jQuery you might quickly run into browser compatibility issues like which event to use for checkbox change.

If you're already using auto-postback in your asp.net webform (as I see quite often, whether it's necessary or not) then this solution should work for you.

add to .aspx:
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True" RepeatLayout="UnorderedList" CssClass="cbList">
</asp:CheckBoxList>
<asp:Label ID="Label1" runat="server" Text="Selected values: nothing." CssClass="tooltipLabel"></asp:Label>

Open in new window

merge into your .aspx.vb:
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            CheckBoxList1.Items.Add("Select All")
            For i As Integer = 1 To 12
                CheckBoxList1.Items.Add("Month " & i)
            Next
            ViewState("CheckBoxList1.AllSelected") = False
        End If
    End Sub

    Private Sub CheckBoxList1_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles CheckBoxList1.SelectedIndexChanged
        Dim blnAllSelected As Boolean = CheckBoxList1.Items(0).Selected
        If ViewState("CheckBoxList1.AllSelected") <> blnAllSelected Then ' user has (un)checked the first item
            For i As Integer = 1 To CheckBoxList1.Items.Count - 1
                CheckBoxList1.Items(i).Enabled = Not blnAllSelected
            Next
            ViewState("CheckBoxList1.AllSelected") = blnAllSelected
        Else ' user has (un)checked another item
            Dim blnAnyOtherChecked As Boolean = False
            For i As Integer = 1 To CheckBoxList1.Items.Count - 1
                If CheckBoxList1.Items(i).Selected Then blnAnyOtherChecked = True : Exit For
            Next
            CheckBoxList1.Items(0).Enabled = Not blnAnyOtherChecked
        End If
        ' show selected values
        Dim strInfoText As String = "Selected values: "
        Dim blnFirst As Boolean = True
        If blnAllSelected Then
            strInfoText &= "all ("
            For i As Integer = 1 To 12
                If Not blnFirst Then strInfoText &= ", "
                strInfoText &= CheckBoxList1.Items(i).Text
                blnFirst = False
            Next
            strInfoText &= ")"
        Else
            For i As Integer = 1 To 12
                If CheckBoxList1.Items(i).Selected Then
                    If Not blnFirst Then strInfoText &= ", "
                    strInfoText &= CheckBoxList1.Items(i).Text
                    blnFirst = False
                End If
            Next
            If blnFirst Then strInfoText &= "nothing"
        End If
        strInfoText &= "." ' ...
        Label1.Text = strInfoText
    End Sub

Open in new window

(optional) add to your .css:
.cbList {
    border: 1px solid red;
}

.tooltipLabel {
    border: 1px solid InfoText;
    color: InfoText;
    background-color: InfoBackground;
}

Open in new window

0
 
Steve KrileCommented:
@robert_schutt - Nice!  Consider the cat skinned.
0
 
shirleyz8821Author Commented:
Sorry for the later response. robert_schutt, you code works perfect, thank you  
&skrile,  although I have no chance to run you code, your ideas and code are excellent. Separate marks to both of you. Very appreciated with your help.
0
 
shirleyz8821Author Commented:
Thank you!
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now