Find selected CheckBoxes in your GridView control

I was recently asked a question on a forum in regards to what rows are selected when you've got an ASP.NET GridView filled with CheckBoxes on a page. The answer is made simple thanks to jQuery. This is the sample table below:

clip_image002

When the user clicks the button they can find all the selected checked check boxes with the following code:

<script language="javascript" type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script language="javascript" type="text/javascript">
$(function() {
$("#GetSelectedValues").click(function(e) {
$("#GridView1 input:checked").each(function() {
alert($(this).next("label").text());
});
e.preventDefault();
});
});
</script>

Nice and simple.

A recommended way would be to add a class to the GridView and then handle this requirement in the following manner:

Add a class attribute to the GridView (say gv)

<asp:GridView ID="GridView1" class="gv">

and access the control like this:

$(".gv input:checked")

This approach would work even in a MasterPage scenario.

1 comment: