How to get the values of the last 4 columns with Jquery

3

I have a panelGrid , and would like to know how to get the last 4 elements before a certain one of the same line.

That is, I have a line, and the last element will receive the sum of the previous four.

Thank you

    
asked by anonymous 05.12.2015 / 19:13

1 answer

1

Using the jQuery selector next to the forEach array function you can select the last 5 elements of the set, add the first 4, and when you reach the last, assign the total value of the sum.

Here's an example:

var total = 0;
Array.prototype.forEach.call($('.columnRight > label'), function(val, idx, arr) {
  if(arr.length > 5 ? idx > arr.length - 6 ? true : false : false) {
    if(idx == arr.length - 1) {
      val.textContent = total;
    } else {
      total = total + parseInt(val.textContent);
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="columnRight">
  <label>1</label>
  <label>2</label>
  <label>3</label>
  <label>4</label>
  <label>5</label>
  <label>6</label>
  <label></label>
</div>

In this line if(arr.length > 5 ? idx > arr.length - 6 ? true : false : false) { I used a ternary operation to avoid if 's nesting, basically it checks if the number of elements in the array is greater than 5, if it checks to see if the current index is greater than the quantity of elements in the array minus six, if yes does the rest of the operation. Understand more about ternary operations here .

The last label has the sum of the values of the 4 before it.

  

See working at jsfiddle .

Reference: MDN - forEach .

    
06.12.2015 / 17:34