Select All CheckBoxes in an ASP.NET ListView Control using jQuery

by Bill Beckelman 9. August 2008 14:54

I have been thinking about doing this since I started using jQuery about a week ago because it is so much cleaner on the client side instead of having to do a postback just to select some CheckBoxes. Turns out it is pretty easy to do if you get your selectors right. Hint: FireBug makes this a lot easier.

image  
Note: The ListView is based on an excellent post by Matt Berseth http://mattberseth.com/blog/2007/11/yui_datatable_styled_listview.html 

Demo | Download

Explanation:

When you add a CssClass to a CheckBox control, the class isn't applied to the checkbox, but instead to a span tag that surrounds the checkbox. With that in mind, you just have to select the spans in your code that have your CssClass applied and then look for a CheckBox in them.

So,

image

becomes this in the source:

image

So now all we have to do is find  the CheckBox that we want to act as our select all control and give it a click event. The click event will need to find all of the spans with our CssClass applied and then the CheckBoxes inside them. The jQuery I used to do this is below:

    $(document).ready(function() 
        { 
            $("#ListViewCustomers_CheckBoxSelectAllItems").click(function() 
            { 
                var checked_status = this.checked; 
                $("td >.selectAllItems >input:checkbox").each(function() 
                { 
                    this.checked = checked_status; 
                }); 
            }); 
                            
        });

I did run into a problem when I tried to throw my ListView into an UpdatePanel. It would work the first time until the panel was posted back, but after that it wouldn't work. It just took a client side pageLoad event to fix things up:

    function pageLoad()
    {
        $(document).ready(function() 
            { 
                $("#ListViewCustomers2_CheckBoxSelectAllInUpdatePanel").click(function() 
                { 
                    var checked_status = this.checked; 
                    $("td >.selectAllItemsInUpdatePanel >input:checkbox").each(function() 
                    { 
                        this.checked = checked_status; 
                    }); 
                }); 
                                
            });    
    }

Hope this helps someone. Please let me know if you use it and make improvements.

kick it on DotNetKicks.com    

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.7
Theme by Mads Kristensen


About Me

I live and work in Salt Lake City, Utah. My background is in aviation. I have a degree in Aeronautical Science from Embry-Riddle Aeronautical University in Prescott, AZ. I have worked as a commercial airline pilot and most recently as a technical advisor for a charter airline.