Pages

Saturday 13 April 2013

Using jQuery with CheckBox and ASP.NET GridView

Open Visual Studio 2010 > Create an ASP.NET site. In the code behind of the Default.aspx page, add the following class which represents a hosting plan:
Now add a GridView control to the aspx page as shown below:
Let us now bind this GridView with the custom Hosting class we created above:
Your GridView should look similar to the following:
All set! It’s time for some jQuery magic now. What we will do is calculate the sum of the ‘AddOn Cost’ column for only those rows that are checked. Use the following jQuery code:
Let us understand this code step by step:
When a checkbox is clicked, we invoke a function called calculateSum() and pass in the column index 4. Note that column numbering starts at one, not at zero. Hence the 4th column index in our example is ‘AddOn Cost’
We then use a selector as shown below, to get only those rows which are checked and return a single column with the specified numeric index, in our case 4. Using the nth-child with the index lets me iterate through each cell using children(). You may also add the GridView ID or the cssclass to the selector if you have more than one GridView’s on the page.
$("tr:has(:checkbox:checked) td:nth-child(" + colidx + ")")
The entire calculateSum() function looks as shown below:
Once we have our selector, we use .each() to iterate over this jQuery object and add the column value to the ‘total’ variable. The parseFloat( ) parses strings into numbers.
The output is as shown below:

No comments:

Post a Comment