Trying to sum db values with a loop

Hi Guys

I’m still a novice what loops are concerned, but I’ve come up with the following. I’m trying to find all the values for a specific name located in the title column. So I run a filter, get the values back, and now I’m trying to sum them to get a total.

Not working yet, any advice will be appreciated!

$w.onReady(function () {
	$w("#dynamicDataset").setFilter(wixData.filter()
		.eq("title", $w('#dropdown1').value))
		.then((amount) => {
			const sumTotal = [];
			for (let i = 0; i < amount.items.value; i++) {
				sumTotal.push(new amount(amount.items[i].toFixed));
			}
			$w("#textSum").text = sumTotal;
		});
});

Hey tiaan,

How are you? Haven’t seen you for a while.

I haven’t tested it, but the following code is closer to what you are looking for:

$w.onReady(function () {
    $w("#dynamicDataset").setFilter(wixData.filter()
    .eq("title", $w('#dropdown1').value))
    .then((amount) => {
        const sumTotal = 0;
        let items = amount.items; // get the array of returned items
        items.forEach(item => {
           sumTotal += item.value; // add each value to sumTotal
        });
        $w("#textSum").text = "" + sumTotal; // make sumTotal a string
    });
});
  • Keep in mind that the results that you want are returned as an array in amount. So, amount.items is the array of returned results.

  • In the code above, I set the variable items to the resulting array amount.items. I then loop through the array using the foreach loop.

  • Finally, I set #textSum to the value by adding sumTotal to an empty string (“”) which forces Javascript to convert the number sumTotal to a string.
    This should give you a good enough push in the right direction to get it working in your code.

Good luck,

Yisrael

Hi Yisrael

Good to hear from you again!

Thank you for the help, I’ll gvie it a go and revert back shortly!

Tiaan

Hi Yisrael

I hope you had a good weekend!

I spent some time on this the last few days, I had some initial errors which I got sorted out, but now I’m stuck on this one (and have been for three days):
undefined is not an object (evaluating ‘amount.items’)

The script currently looks like this:

export function button7_click(event, $w) {
    $w("#dynamicDataset").setFilter(wixData.filter()
    .eq("title", $w('#dropdown1').value))
    .then((amount) => {
        const sumTotal = 0;
        let items = amount.items;
        items.forEach(item => 
        {sumTotal + item.value;
        });
        $w("#textSum").text = "" + sumTotal;
    });
}

I’ve played around with all sorts of things, changing the amount column from text to number in the db, parseFloat’ing the text, replacing my dropdown1 with a static value to reference against, the list goes on…

I’ve had no luck no matter what I try, the system always gives this error. And after about 40+ articles, I’m none the wiser… Any idea what could be causing this?

Thank you
Tiaan

A great weekend! Thanks.

The error message that you’re getting means that the query did not return any results. That is, amount.items is undefined. Maybe there are no results based on the filter. You can check to see if you’re getting results by adding a console.log(amount.items); right after the then( ) statement.

I’m running the same query to display all the results in a repeater, and this works.

Then I though, perhaps it’s running a refresh of the dropdown everytime I click the button, so I hardcoded a filter item which I know is in the database, but still no luck…

Post the URL so I can inspect. Maybe I’m having a be dumb moment.

BTW - did you try the console.log()?

LOL, I doubt that… It’s a securely hidden page on a live financial site, so I can’t share here, but I’ll try to give some more contecxt on the page below.

I’m running the consol.log(), it still gives me this error:

TypeError: undefined is not an object (evaluating ‘amount.items’)

What I do first is to build the dropdown items from the available items in the database as they will change on a daily basis.

I then have a repeater that’s connected to #dynamicDataset and successfully filters with the script below:

export function dropdown1_change(event, $w) {
	$w("#dynamicDataset").setFilter(wixData.filter()
		.eq("title", $w('#dropdown1').value))
		.then((results) => {
			console.log("Dataset is now filtered");
			$w("#table1").rows = results.items;
		}).catch((err) => {
			console.log(err);
		});
}

Then, I want to use this same dropdown value as my filter to calculate to total for all the values that I’ve just filtered and am displaying on my table with this script:

export function button7_click(event, $w) {
	$w("#dynamicDataset").setFilter(wixData.filter()
			.eq("title", $w('#dropdown1').value))
		.then((amount) => {
			console.log(amount.items);
			const sumTotal = 0;
			let items = amount.items;
			items.forEach(item => {
				sumTotal + item.value;
			});
			$w("#textSum").text = "" + sumTotal;
		}).catch((err) => {
			console.log(err);
		});
}

Sorry, but I don’t see anything wrong. Without actually seeing the site code itself I don’t have the proper context to understand it.

Maybe you could clone the site and get rid of the sensitive information so I can look at the code. Otherwise, I don’t know what I can do.

BTW - why not just calculate the total right after $w(" #table1 ").rows = results.items;

I understand. Let me set something up and I’ll post it here.

I acutally don’t know why I even bothered with code for the repeater, this filter does all the work, just twice, so I’ve removed that now.

I’ll check back in in 10min with a link!

Here you go:

https://tiaanrich.wixsite.com/mysite/test/1234

Hey Tiaan,

Wow! Take me out back and shoot me.

I was trying to use the dataset like using the collection directly. Wrong, wrong, wrong. :exploding_head:

Here’s the corrected code with comments:

export function button1_click(event, $w) {
    
   // no need to set the filter on the database since it's still set

   // how many items filtered in the dataset?
   let count = $w("#dynamicDataset").getTotalCount();
	
   // get all of the items
   $w("#dynamicDataset").getItems(0, count)
   .then((results) => {
	let sumTotal = 0; // declare sum
	let items = results.items;
	items.forEach(item => {
	   // the amount is a string so convert
	   sumTotal = sumTotal + Number(item.amount);
	});
	$w("#textSum").text = "" + sumTotal;
	}).catch((err) => {
	   console.log(err);
	});
}

OK - so I’m embarrassed. :see_no_evil:

I made the changes in the test project you set up and saved them there as well. Give it a try.

I’m now gonna go cry in my beer.

All the best,

Yisrael

6 Likes

Hi Yisrael

Thank you for taking the time to help me out with this!

LOL!! I’ll give it a quick go… I hope your confidence will recover! ////

All the best,
Tiaan

1 Like

I’ll live.

1 Like

This works great, thank you! I published the site, it’s available here for anyone wanting to try something similar:
https://tiaanrich.wixsite.com/mysite/test/1234

Yisrael’s working code:

export function button1_click(event, $w) {
    
   // no need to set the filter on the database since it's still set

   // how many items filtered in the dataset?
   let count = $w("#dynamicDataset").getTotalCount();
	
   // get all of the items
   $w("#dynamicDataset").getItems(0, count)
   .then((results) => {
	let sumTotal = 0; // declare sum
	let items = results.items;
	items.forEach(item => {
	   // the amount is a string so convert
	   sumTotal = sumTotal + Number(item.amount);
	});
	$w("#textSum").text = "" + sumTotal;
	}).catch((err) => {
	   console.log(err);
	});
}
4 Likes

Thanks Yisrael! Helped me too!

2 Likes

I send a big virtual fist bump for you guys for grinding through this!! This came through right on time for what I need. Thanks for sharing and contributing!!

1 Like

Hello Tiaan
I saw your website https://tiaanrich.wixsite.com/mysite/test/1234
I need to make this
I’m a begginer in WIXCode
can I to see inside your website?

Hi Maxwell

See this post above from 12 Mar, this is basically the only code on the website:

Let me know if you need clarification on anything. Good luck!
Tiaan