# Randomising CMS content & refresh button issue

**URL:** <https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036>\
**Category:** Ask the community\
**Tags:** wix-data, cms, code, wix\
**Created:** [August 25, 2025, 7:45pm UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036 "2025-08-25T19:45:03Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Linda\_Oldfield](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/linda_oldfield/32/101237_2.png) [@Linda\_Oldfield](https://forum.wixstudio.com/u/Linda_Oldfield)\
**Post date:** [August 25, 2025, 7:45pm UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/1 "2025-08-25T19:45:03Z")

</div>

**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

```javascript
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);
            });
    });
  
        }
)

```

---

<div class="post-metadata">

**Author:** ![V-Blog](https://avatars.discourse-cdn.com/v4/letter/v/898d66/32.png) [@V-Blog](https://forum.wixstudio.com/u/V-Blog)\
**Post date:** [August 26, 2025, 3:20am UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/2 "2025-08-26T03:20:45Z")

</div>

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.). -

```javascript
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();
    });
});

```

---

<div class="post-metadata">

**Author:** ![Linda\_Oldfield](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/linda_oldfield/32/101237_2.png) [@Linda\_Oldfield](https://forum.wixstudio.com/u/Linda_Oldfield)\
**Post date:** [August 26, 2025, 5:26am UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/3 "2025-08-26T05:26:17Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![V-Blog](https://avatars.discourse-cdn.com/v4/letter/v/898d66/32.png) [@V-Blog](https://forum.wixstudio.com/u/V-Blog)\
**Post date:** [August 26, 2025, 7:41am UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/4 "2025-08-26T07:41:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![Linda\_Oldfield](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/linda_oldfield/32/101237_2.png) [@Linda\_Oldfield](https://forum.wixstudio.com/u/Linda_Oldfield)\
**Post date:** [August 27, 2025, 4:09am UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/5 "2025-08-27T04:09:53Z")

</div>

It worked!! Thanks so much 😃

---

<div class="post-metadata">

**Author:** ![noaya](https://sea1.discourse-cdn.com/wix/user_avatar/forum.wixstudio.com/noaya/32/37956_2.png) [@noaya](https://forum.wixstudio.com/u/noaya)\
**Post date:** [December 18, 2025, 2:26pm UTC](https://forum.wixstudio.com/t/randomising-cms-content-refresh-button-issue/73036/6 "2025-12-18T14:26:21Z")

</div>

I love how threads get so detailed that you could drop in a sentence like “please continue scrolling, nothing to see here” and it becomes invisible.
