Hi, I’m new to coding so I am trying as I can. Is there a way to make a button that is pressed then the text box will display a random item from a specific field from a collection? Thank you so much!
Yes. The easiest way will be by installing the wix-data-helpers Velo package and call the getRandomItem(‘CollectionId’) function.
https://support.wix.com/en/article/velo-working-with-velo-packages-built-by-wix
I’m sorry but I still don’t understand what is going on in there
So I tried to copy the code to the site then change “collectionID” to my actual collection, but then I don’t know how to make it connect to the button. I tried this code and I might somehow fix it wrong:
$w ( ‘#button1’ ). onClick (() => {
getRandomItem ( ‘RandomCards’ )
. then (( randomNumber ) => {
$w ( ‘#themename’ ). text = randomNumber.name ;
})
. catch (( error ) => {
console . error ( error );
});
//...
.then(item => {
$w('#button1').label = item.name;
$w('#button1').link = `/${item.page}`; //if you want to navigate to another page on click;
})
I’m sorry but I tried it and didn’t work. I think the code I typed in is a whole mess now. Can you check for me what I did wrong, please?
import wixData from ‘wix-data’ ;
export async function getRandomItem ( RandomCards ) {
try {
const numberOfItems = await wixData . query ( RandomCards ). count ();
**if** ( numberOfItems === 0 ) {
**return** **null** ;
}
**const** randomNumber = Math . floor ( numberOfItems * Math . random ());
**const** { items } = **await** wixData . query ( RandomCards ). skip ( randomNumber ). limit ( 1 ). find ();
**return** items [ 0 ];
} catch ( error ) {
return Promise . reject ( new Error ( Failed to getRandomItem - original error - ${ error.message }
));
}
}
$w . onReady ( function () {
$w ( ‘#themename’ ). text = ‘Theme Name’ ;
$w ( '#button1' ). onClick (() => {
getRandomItem ( 'RandomCards' )
. then ( item => {
$w ( '#button1' ). label = item.name ;
})
. **catch** (( error ) => {
console . error ( error );
});
});
Thank you so much!
collection ID is RandomCards
the field key is title