After several fuzzy explanations here and hard trying during months of frustration I have finally made a 5 star rating work. Experts here are good at coding but almost none seem to be pedagogic when it comes to instructions for amateurs.
First of all, make sure that your related collection is made or changed to “custom” and during the creating and testing of the rating function you shall enable everything for anyone to avoid unecessary confusion (put restrictions afterwards).
Then create a dataset at the page called “Rating dataset”.
Connect this dataset to the collection that is related to the article, video or photo you wanna have rated.
In the collection you shall create 3 new fields and all of them shall be of the type # Number.
Name field one to Average (field key: avg).
Beneath it → write 5
Name next field to Total ratings (field key: totalRatings).
Beneath it → write 5
Name the third to Rating sum (field key: ratingSum).
Beneath it → write 1
Ps! The first rating must be written in manually because the Average field must be a number between 1-5. The reason to why I put 5 is that if you start with a lower digit I guess that you never can get 5 as total rating (maybe only 4.5 but I can be wrong). Please comment this if you allready know.
You need a rating input element so click at + (Add) and go to Input → Ratings Input → Chose the first one with the yellow stars and add it to the page.
When having this element marked → add an event handler named OnChange.
OBS! You shall NOT connect the Ratings input element to the Ratings dataset so just leave it.
Then you need a rating display element by going to Rating Display and choose the first one with the stars. Add it to the page and connect it to the Rating dataset. When having this opened, make the following choises:
“Rating value connects to” → Average
“Number of ratings connects to” → Rating sum.
Turn on Dev mode (if you have not already done that) and use this code:
export function ratingsInput_change ( event ) {
$w ( “#dataset3” ). onReady (() => {
const currentItem = $w ( “#dataset3” ). getCurrentItem ();
const average = currentItem . avg ;
const count = currentItem . ratingSum ;
const total = currentItem . totalRatings ;
const newRating = $w ( ‘#ratingsInput’ ). value ;
const newAverageLong = ( total + newRating ) / ( count + 1 );
const newAverageShort = Number . parseFloat ( newAverageLong ). toFixed ( 1 );
$w ( ‘#dataset3’ ). setFieldValues ({
‘avg’ : newAverageShort ,
‘totalRatings’ : total + newRating ,
‘ratingSum’ : ( count + 1 )
});
$w ( ‘#dataset3’ ). save ()
console . log ( “Rating completed.” )
});
}
Now test if it works as it should by doing some ratings. Refresh your browser after each rating.