I have quite similar case.
I have multiple datasets where member connect to each dataset at some point. I want to sumTotal fields, which are multi reference fields from another datasets. Final result should be displayed in a text item. Any help would be appreciated.
Hi,
thank i saw that. unfortunately it does not sum up values, displays them as a text only. Could you check it on previous discussio where you placed code. @ahmadnasriya
Sure, you need to run a forEachItem( ) loop on the repeater to sum the values, for example, if you have a repeater that shows the price of products, and you want to show the total, you can do it like this:
let total = 0; // A variable to store the total.
// Loop through the items to get the price of each one and sum it up.
$w('#repeater').forEachItem(($product, productData) => {
total += productData.price;
})
console.info(total); // Print the total to the console.
$w('#total').text = String(total); // Show the total in a text element on the screen
If you have an input field on each repeated item that you want to enter a value for each item, and sum them all up, you can use the selector of the repeater scoop.
let total = 0; // A variable to store the total.
// Loop through the items to get the entered number
$w('#repeater').forEachItem(($item) => {
total += $item('#input').value;
})
console.info(total); // Print the total to the console.
$w('#total').text = String(total); // Show the total in a text element on the screen
Hi,
Thanks, it helps a lot! I get it now how to get each value.
But there’s one more problem, the result was not summing the value instead combining it, here’s the result
@ajib18j The input field type should be “Number”, otherwise, you need to convert the text value of the input field into a number, here’s how:
// 1: Store the text value in a variable
const stringValue = $w('#input').value;
// 2: Convert the text value into a numeric value
const numericValue = Number(stringValue);
// Or convert it immediately
const numericValue = Number($w('#input').value);
So, the code was combining them because it treats them as strings, not as numbers, now that they’re numbers, it’ll sum them instead of combining them.
@ahmadnasriya Thank you so much, it works perfectly!
but I am facing another problem. I want to save the result to my collection table. but it seems my code is not working
@ajib18j Yes, you’re increasing the value of the variable before declaring it, the declaration must be before the use of any instance.
Try this instead:
// total: is a variable declared to store the sum value;
// Now before you update an entry, you need to get it first by performing a query.
return wixData.query('stok-basic').eq('fieldId', fieldValue).find().then((x) => {
let item = x.items[0]; // The item that we need to update it.
// Updating the item "total" field with the total value;
item.total = total;
// Attempt the update ...
return wixData.update('stok-basic', item);
})