PsychoX
PsychoX

Reputation: 1098

jQuery sum values from items above

I have small problem.

What I want to achieve is adding sum of values from above elements to each one. For example every position have got it own time value hidden in attribute. I can get it by using jQuery

var time = $(ui.draggable).attr("time");

now we got 4 positions with time as follows:

  1. 432 sec
  2. 123 sec
  3. 5634 sec
  4. 654 sec

Now I want to sum it like this:

1. 432
2. 432+123
3. 432+123+5634
4. 432+123+5634+654

Any ideas how can I do this?

This is my code:

$(document).ready(function(){

    $(".trash").sortable({
        tolerance: 'touch',
        receive: function (event, ui) {
        ui.item.remove();
           }
    });
    $(".DragContainer_dest").sortable({helper:'clone',
        opacity: 0.5,
        connectWith: '.trash',
        scroll: true,
        update : function () { 
        var order = $('.DragContainer_dest').sortable('serialize',{key:'string'}); 
        $.post('includes/ajaxify.php',order+'&action=update');    
        var time = $(this).attr("time");
        },
        out : function () { 
            ui.item.remove();
        }
    });

    $("div[class=DragContainer] .DragBox").draggable({helper:'clone'}); 

    $(".DragContainer_dest").droppable({
        accept: ".DragBox",
        tolerance: "touch",
        drop: function(ev, ui) {
           $(this).append($(ui.draggable).clone().addClass("added"));  
        }
    });
  });

I want every element dropped or sorted in DragContainer_dest to sum values from other elements above him. Can this be done?

Upvotes: 0

Views: 3954

Answers (3)

Igor Zinov'yev
Igor Zinov'yev

Reputation: 3706

As I can understand, you need to collect all siblings of a node that come before the element in question and collect their attributes. Let's try this:

var nodeSiblings = $(this).parent().children();
// We need to find the index of our element in the array
var stopIndex = nodeSiblings.index(this);
var time = 0;

nodeSiblings.each( function(index, element){
    if (index > stopIndex) return;
    var attribute = parseInt($(element).attr("time"), 10);
    if (!isNaN(attribute)) time += attribute;
});

// Here you have the sum of all time attributes
alert(time);

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30520

If you're using parseInt as instructed elsewhere, don't forget to include the radix:

parseInt($(ul.draggable).attr('time'), 10);

If you have a zero at the start it will treat it as octal unless you specify the radix.

Upvotes: 0

David Hellsing
David Hellsing

Reputation: 108500

Maybe add a global variable called timeSum and then increase it for each element dropped?

var timeSum = 0;

$(".DragContainer_dest").droppable({
    drop: function(ev, ui) {
       timeSum += parseInt($(ul.draggable).attr('time'));
    }
});

Upvotes: 0

Related Questions