Hello, I’m new a user in Wix and Wix Code. I have a collection that contains few columns and few rows, each cell contains a number. I wont to let member in my website, to push a button and get a random row from the collection. Any idea? Thanks
You can try something like this (with a dataset):
$w.onReady( () => {
$w("#myDataset").onReady( () => {
let count = $w("#myDataset").getTotalCount();
$w("#myDataset").getItems(Math.floor(Math.random() * (count - 1)), 1)
.then( (result) => {
let item = result.items[0];
$w("#text1").text = item.title //an example. Populate your own elements and your own fields. alternatively you can set a filter with item._id
})
})
})
[UPDATED]
Thanks for the code.
“#myDataset” should replace to my collection name?
Let say that I’ve added a button to my page (the page connected to my collection) and also I’ve connected the button the my collection. What is the full code I need to place in my page code, to make this button collect random row from my databset and display it somewhere in the page?
Thank you so much.
@alomoshe “#myDataset” should be replaced to a dataset you add to your page.
If you want to work directly with your collection, the code should be different. something like:
import wixData from 'wix-data';
wixData.query("MyCollection")
.limit(1000)
.find()
.then((res) => {
let items = res.items;
let randomRow = items[Math.floor(Math.random() * (items.length - 1))];
$w("#text1").text = randomRow.title //an example. Populate your own elements and your own fields.
})
Thanks J.D. I’ll try to work with it.