Randomising CMS content & refresh button issue

I’m having trouble with
I have created individual dynamic pages to display workout plans based on a users selections (at the gym, 30 mins, training chest, back, and shoulders, for example).

I have managed to get the code to a point where it’s randomly displaying a set number of results (3), but I need it to only show one result per body part (ie: randomly display one exercise from chest, one from back, and one from shoulders). It’s currently randomising but showing not showing one from each (it might show 2 chest and 1 shoulders for example).

This is currently in a collection in the CMS, with individual columns for body part/muscle, exercise, and sets/reps. There are about 10 exercises per body part/muscle.

Secondly, I have added a button to allow the user to reload the content in the table if they’d like to, but I can’t seem to get this to work.

My current code is below, thanks in advance!

Working in
Wix Editor

import wixData from 'wix-data';

$w.onReady(function () {
  // Add an event listener to your refresh button
  $w("#button1").onClick(() => {
    // Refresh the dataset connected to your table
    $w("#dataset1").refresh()
      .then(() => {
        console.log("Dataset refreshed successfully.");
        // Optional: Add any further actions after refresh, e.g., show a success message
      })
      .catch((error) => {
        console.error("Error refreshing dataset:", error);
        // Optional: Handle errors, e.g., display an error message
      });
  });
});


$w.onReady(function loadRandomExercises() {

    $w("#table1").columns = [{
            "id": "title_fld", // ID of the column for code purposes
            // The field ID in the collection whose data this column displays  
            "dataPath": "title_fld",
            "label": "Exercise", // The column header
            "width": 100, // Column width
            "type": "string", // Data type for the column

        },
        {
            "id": "description_fld", // ID of the column for code purposes
            // The field ID in the collection whose data this column displays  
            "dataPath": "description_fld",
            "label": "Muscle Group", // The column header
            "width": 100, // Column width
            "type": "string", // Data type for the column

        },
        {
            "id": "imagealttext_fld", // ID of the column for code purposes
            // The field ID in the collection whose data this column displays  
            "dataPath": "imagealttext_fld",
            "label": "Sets & Reps", // The column header
            "width": 100, // Column width
            "type": "string", // Data type for the column
        }
    ]
    function shuffleArray(array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]]; // Swap elements
        }
        return array;
    }
        $w.onReady(function () {
        const collectionName = "AtHome-Starter"; // Replace with your actual collection name
        const tableId = "#table1"; // Replace with your actual table element ID

        wixData.query(collectionName)
            .find()
            .then((results) => {
                let items = results.items;
                items = shuffleArray(items);
                items = items.slice(0, 3); 

                // Optional: Limit to a specific number of random items
                // items = items.slice(0, 5); // Example: show 5 random items

                $w(tableId).rows = items; // For tables, use .rows instead of .data
            })
            .catch((error) => {
                console.error("Error loading random items:", error);
            });
    });
  
        }
)

Try following code. The code assumes your description_fld contains body part names like “chest”, “back”, “shoulders”. You may need to adjust the targetBodyParts array to match the exact format in your collection (e.g., “Chest”, “CHEST”, “Pectorals”, etc.). -

import wixData from 'wix-data';

$w.onReady(function () {
    $w("#table1").columns = [{
            "id": "title_fld",
            "dataPath": "title_fld", 
            "label": "Exercise",
            "width": 100,
            "type": "string"
        },
        {
            "id": "description_fld",
            "dataPath": "description_fld",
            "label": "Muscle Group",
            "width": 100,
            "type": "string"
        },
        {
            "id": "imagealttext_fld",
            "dataPath": "imagealttext_fld",
            "label": "Sets & Reps",
            "width": 100,
            "type": "string"
        }
    ];

    const targetBodyParts = ["chest", "back", "shoulders"];
    
    function loadRandomExercises() {
        const collectionName = "AtHome-Starter";
        const tableId = "#table1";

        wixData.query(collectionName)
            .find()
            .then((results) => {
                let allItems = results.items;
                let selectedExercises = [];

                targetBodyParts.forEach(bodyPart => {
                    let exercisesForBodyPart = allItems.filter(item => 
                        item.description_fld && 
                        item.description_fld.toLowerCase().includes(bodyPart.toLowerCase())
                    );
                    
                    if (exercisesForBodyPart.length > 0) {
                        const randomIndex = Math.floor(Math.random() * exercisesForBodyPart.length);
                        selectedExercises.push(exercisesForBodyPart[randomIndex]);
                    }
                });

                $w(tableId).rows = selectedExercises;
            })
            .catch((error) => {
                console.error("Error loading random exercises:", error);
            });
    }

    loadRandomExercises();

    $w("#button1").onClick(() => {
        loadRandomExercises();
    });
});

Thank you, I will try this! Am I best to delete and replace the code with above, or just make the changes you’ve suggested to existing?

Replace it. I haven’t tested the code but it should work. Make sure to add keywords in description.

It worked!! Thanks so much :smiley: