3
I have a panelGrid
, and would like to know how to get the last 4 elements before a given of the same line.
That is, I have a line, and the last element will receive the sum of the previous four.
Thank you
3
I have a panelGrid
, and would like to know how to get the last 4 elements before a given of the same line.
That is, I have a line, and the last element will receive the sum of the previous four.
Thank you
1
Using the jQuery selector together with the array function forEach
you can select the last 5 elements of the set, add the first 4 and when you arrive at the last assign the total value of the sum.
Following 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>
<div class="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 a nesting of if
's, basically it checks whether the amount of elements in the array is greater than 5, if it checks whether the current index is greater than the amount of elements in the array minus six, if it does the rest of the operation. Learn more about ternary operations here.
The last label
has the sum of the values of the 4 previous to it.
See working on jsfiddle.
Reference: MDN - foreach.
It worked, I had already succeeded with a smaller but less elaborate function than yours, but its works better remembering that in my case the number is a String
and had along the R$
and needed to treat.
Browser other questions tagged jquery jsf primefaces
You are not signed in. Login or sign up in order to post.
Do you have any code to post ? can illustrate your question better ? not understood clearly.
– Lucas Fontes Gaspareto
I would like to have taken the last 5 elements of a query, I did using the following:
$('.columnRight > label').slice(-5)
.– Macario1983