简体   繁体   中英

Why is my localStorage checkbox/boolean value comparison not working for my Google Chrome Extension?

I have successfully mapped a boolean variable to my localstorage variables which is triggered by a checkbox on my options.html page for my Chrome extension.

What I want know is what the best way to show/hide an element based on whether that checkbox is checked in options on my popup.html (browser button event.) The following jQuery $("#myElement").hide(); does not work - nor would I expect it to... but I'm sort of at a loss as the best way to control displaying those elements to the end user.

Note: display: none for CSS is an option too - I just don't know the best way to go about this.

   var value = localStorage["myCheckbox"];
   alert(localStorage.getItem('store.settings.myCheckbox'));

   if (value != null)
        alert(value);//this works (true if checked, false if not checked...)

    if (!value){
        alert('hide the element'); 
        $("#myElement").hide(); //hide a div element in my popup (chrome extension button popup)
    }

I'm assuming that you are assigning the .checked property of your checkbox to localStorage["myCheckbox"] , so, since that localStorage variables can only be strings , it can be either "true" or "false" , depending on the checkbox's state.

Your error is doing this:

if (!value) { 
    ...
}

the above condition will never be satisfied , because a non-empty string (such as "true" or "false") is always true in JavaScript, so !"string" is always false. Hence, to check the value of your checkbox in your popup.js you should do:

var isChecked = localStorage.myCheckbox === "true";

if (!isChecked) $('#myElement').hide();
// if the checkbox is not checked hide the element

Alright I fixed the first issue - (it was returning strings so I needed to use ===)

However I still need to figure out the best way to do part 2 - the show/hide functionality. I will post a new question and update this with the link. Thanks so much for your help, Marco!

   var value = localStorage["myCheckbox"];
   var isChecked = localStorage.getItem('store.settings.myCheckbox');

    if (isChecked === "false"){ 
    alert('its FALSE');
    $('#myElement').hide();
    }

    if (isChecked === "true"){
    alert('its TRUE');
    $('#myElement').show();
    }

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