Update collection from switch

Question:
Does anyone know how to use an onClick() function to update a boolean value in a collection?

One of my users wants to control the pages on which sponsors appear. I set up a boolean value, attached it to a switch, and added a button to save the record. But it’s rather clumsy and he often forgets to click Save. It occurs to me that I should be able to save the changed record with an onClick but i have no idea how.

Thoughts?

Hi there, you can place the button code directly inside the onChange property of the switch, something like this:

import wixData from 'wix-data';

$w("#mySwitch").onChange( (event) => {

    let isChecked = $w("#mySwitch").checked;
    
    let toUpdate = {
    "_id": "00001",
    "bool": isChecked,
    };
    
    wixData.update("myCollection", toUpdate)
    .then((results) => {
    console.log("ITEM UPDATED");
    })
    .catch((err) => {
    console.log(err);
    });

});