Adding the values of a cfgrid column

We were asked about solving the problem of adding the values of a column in a flash cfgrid, so we made an example in response.

The cfgrid shows the items of a shopping cart. The quantity column is editable, so we can change the number of items we want to buy. Then, we click "Calculate Order" and the total shows at the bottom. Although we are triggering the addition at the button's onclick event, we could do the same at the cfgrid onchange. The relevant part is when we get the column value and add it to the total.


We were asked about solving the problem of adding the values of a column in a flash cfgrid, so we made an example in response.

The cfgrid shows the items of a shopping cart. The quantity column is editable, so we can change the number of items we want to buy. Then, we click "Calculate Order" and the total shows at the bottom. Although we are triggering the addition at the button's onclick event, we could do the same at the cfgrid onchange. The relevant part is when we get the column value and add it to the total.

To get a specific column in row i:

cart.getItemAt(i)['price']; //where price is the name of the column and cart is the name of the grid

In addition, we are changing the value of the subtotal column with the price multiplied by the quantity in row i:

cart.editField(i, 'amount', subTotal); //where amount is the name of the column we want to edit

The complete code:

var totalAmount = 0; var item; var subTotal = 0; for(var i = 0; i < cart.length; i++) { item = cart.getItemAt(i); //get subtotal subTotal = number(item['price']) * item['quantity']; //tally the amount up totalAmount += subTotal; //change the subtotal column for this row cart.editField(i, 'amount', subTotal); } //show the total total.text = totalAmount;

Note that if we have many rows this may not be the best method as it may cause the "A script in this movie is causing Flash Player to run slowly" alert. We can avoid it by using a different technique. More on that in my next post.

Live example
Download the source