简体   繁体   中英

disable restarting a quiz in javascript and html

i'm looking for a way to disable a start button on a quiz after its clicked and still be disabled if the user were to refresh the browser.

its quite a large script and everything I try seems to either disable the button without an input or do nothing.

You can create a cookie in the browser when the start button is clicked, and then check for that cookie, If the cookie exists set that button as disabled. even if the page is reloaded that cookie will be there and the start button will be disabled until the cookie is destroyed. You can create a cookie in js like this and set its expiry according to the requirement:

document.cookie = "username= your_username; expires=Thu, 18 Dec 2022 12:00:00 UTC";

You can try using localStorage to store persistent data, and then retrieve it when the page loads

const key = 'your_key_here';
const isDisabled = !!+localStorage.getItem(key);

document.getElementById('btn').disabled = isDisabled;

function handleClick (e) {
  localStorage.setItem(key, 1)
}
<button id="btn" onClick="handleClick" />

Be aware that it will stay indefinitely in localStorage until you clear it

Try to keep a flag in cookie or session/local storage.

For instance, if you click the button on start of quiz, add click event listener to the button and inside of it push a variable in the cookie or session/local storage. You can then check for this variable in your script whenever your page loads. If the variable is present, disable the button using JavaScript else let it be enabled.

But be sure to check the difference between session storage and local storage before using them. They both have different use cases and will depend on what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM