Persistent checked ons-switch
-
I’m trying to keep a checked ons-switch to remain checked even after directing to other page, my code isn’t exactly doing that.
function offWork() { if (document.getElementById("grabOrder").style.display == "none") { localStorage.setItem('swButton', 'true'); //trying to store the value of ons-switch = true document.getElementById("grabOrder").style.display= "block"; } else { localStorage.setItem('swButton', 'false'); //trying to store the value of ons-switch = false document.getElementById("grabOrder").style.display= "none"; } }
I thought of creating a function checkSwitch() to check the value of the switch and be called when home.html is opened, where the ons-switch resides.
function checkSwitch() { if (document.getElementById('swButton').checked == (localStorage.getItem("swButton") === 'true')) { document.getElementById('swButton').setAttribute('checked',true); } else { document.getElementById('swButton').setAttribute('checked',false); } }
HTML ons-switch:
<div class="right"><ons-switch id="swButton" onclick="offWork()"></ons-switch></div>
Any advice would be great.
-
@AspiringWizard This code was pulled from one of my working apps:
Initialize the storage variable
if (localStorage.getItem("startVibrate") === null) { localStorage.setItem('startVibrate', 'true'); }
Settings Page -> In the onShow event listener
document.getElementById('startVibrate').checked = (localStorage.getItem("startVibrate") === 'true'); document.getElementById('startVibrate').addEventListener('change', function(e) { localStorage.setItem('startVibrate', e.target.checked.toString()); });
Markup
<ons-switch id="startVibrate"></ons-switch>
-
Tried implementing your code, I’m getting “Cannot set property ‘checked’ of null”
document.getElementById('swButton').checked = (localStorage.getItem("swButton") === 'true');
-
@AspiringWizard As I stated in the earlier post, that code is implemented in the settings page onShow event listener. You would need this:
document.addEventListener("show", function(event){ if (event.target.id == "myOnsPageID") { document.getElementById('swButton').checked = (localStorage.getItem("swButton") === 'true'); document.getElementById('swButton').addEventListener('change', function(e) { localStorage.setItem('swButton', e.target.checked.toString()); }); } });
Edit: You probably don’t need the
toString()
but I come from the background with explicit types, so I often feel I should still do this in JS to avoid any type of unintended issues.
-
Sorry for the delay, I had to work on other parts of my project before coming back to this. I have managed to get my ons-switch working as intended with your code, thanks for your help!