refer to:Calculate Sum of ASP.NET CheckBox Values using jQuery

In this article, we will see how to add values of multiple ASP.NET Checkboxes using jQuery. This example could be useful in scenarios where users are asked to select services they would like to avail and each service has a rate displayed – like in a webhosting service. Using jQuery, the total service cost should be automatically calculated, as the services are selected.

Note: If you are using jQuery with ASP.NET Controls, check out my EBook called 51 Recipes with jQuery and ASP.NET Controls.

Create an ASP.NET Website. Add the following markup

checkbox layout html

The layout should look similar to the following:

checkbox layout

Now add a reference to the latest jQuery script file and write the following code:

Sum checkbox jquery

Let us see what we just did:

When a checkbox is clicked, a variable ‘checked’ keeps track of the checked checkboxes.

checked variable

We then iterate the ‘checked’ collection using $().each() and add the text of the checkbox to a variable ‘total’.

calculate checkbox sum

Observe how we are accessing the value of a checkbox using $(this).next().text());

This is because the checkbox gets rendered like this:

checkbox render

To access the value, which is inside the label, we use next() which finds the very next sibling of each checkbox, which in our case is the label control. The parseFloat( ) parses strings into numbers.

The result is displayed in a paragraph (tot) using the toFixed() method, which rounds the result to the specified number of decimal places, in our case 2.

$('#tot').text("Your Total Amount Is: " + total.toFixed(2));

The output is shown here:

jquery checkbox demo

See a Live Demo. This demo has been tested in the following browsers: IE 7, IE 8, Firefox 3, Chrome 2, Safari 4.

The entire source code of this article can be downloaded over here

posted on 2011-07-18 13:45  沸石  阅读(122)  评论(0)    收藏  举报

导航