remibenault
remibenault

Reputation: 25

How to save checkbox value in localStorage?

I'm stuck about saving checkbox value inside localStorage, I found some topics about here but I still get issue with.

Here is part of my HTML that creates the checkbox :

<div id="displayer_show">
    <div class="demo" id="labels2-3">
        <input name="switch_show" type="checkbox" value="1" checked/>
     </div>
</div>

And part of my main script :

$(function () {
    var data = localStorage.getItem("showning");
    if (data !== null) {
        $("input[name='switch_show']").attr("checked", "checked");
    }
});

$("input[name='switch_show']").click(function () {

    if ($(this).is(":checked")) {
        localStorage.setItem("showning", $(this).val());
    } else {
        localStorage.removeItem("showning");
    }
});

There is jsfiddle link of it : http://jsfiddle.net/remibenault/Dp4Tj/8/

Any help will be appreciated.

Upvotes: 1

Views: 4817

Answers (2)

Bogdan Savluk
Bogdan Savluk

Reputation: 6312

Edit your script as following:

$(function () {
  var data = localStorage.showning;
  $("input[name='switch_show']")
    .prop('checked',data=='true')
    .change(function () {
       localStorage.showning = $(this).prop("checked");
    });
});

The problem is that checkbox is checked by default, and you

Upvotes: 4

soktinpk
soktinpk

Reputation: 3888

Just remove the value="1" checked part and you're fine. Also $(this).val() should be 1. I'm not quite sure why you're calling $(this).val().

http://jsfiddle.net/prankol57/Dp4Tj/9/

Upvotes: 1

Related Questions