'How to store and retrieve checkbox state on refresh of page? Mongoose/EJS/Nodejs/Express

I have a checkbox, essentially like a to do list. When i check the box, I want to retain the state even after i refresh the page by using mongoose. I do know of localstorage, however EJS runs on a server side. Currently I am able to post the checkbox to my express side.

IN EJS

form id="form2" action="/check" method="post"></form>
<input form="form2" type="checkbox" name="checkboxx" onChange="this.form.submit()">

IN EXPRESS

app.post("/check", function(req,res){
  Item.updateOne({checked: req.body.checkboxx.checked}, function(err){
    if(err){
      console.log(err);
    } else console.log("successfully updated db")
  })
  
  res.redirect("/")
})

My collection is "Item", the schema includes a boolean property "checked" checkboxx is the name of the input checkbox. Any way to update the information of the checkbox state and reload the saved states upon refreshing the page?



Solution 1:[1]

In my case, the user profile page is also a form for data entry. (I save the form values with mongoose on a Mongo Atlas db, so some steps are skipped here.)

In my profile.ejs page, the toggleswitch is :

<div class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" name="onOffSwitch" id="onOffSwitch" <%= params.onOffSwitch ? "checked" : "" %> >
  <label class="custom-control-label" for="onOffSwitch">Activate</label>
</div>

And in my Express app the route is :

app.post(`/api/params`, isLoggedIn, (req, res) => {
    const email = req.user.email;
    const onOffSwitch =req.body.onOffSwitch;
    });
    res.redirect(`/profile`);
});

Even after a log out and re-login, the checkbox value gets releaded correctly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lorenzo Sandini