0

I am trying to set data on localStorage as 1/0.Then if I get 1 from it I want to checked a checkbox else unchecked.I was wrote a code but it isn't working.And I can't find-out what I am doing wrong!

<label class="a-b-c">
  <input id="check-it" type="checkbox" name="check">
  Check.
</label>

$(window).load(set_func_o());
    function set_func_o(){
        try_it();
        $('#check-it').change(function(){
            var chk= this.checked ? '1':'0';
            localStorage.setItem('checkit-the-item',chk);
            try_it();
        });
        function try_it(){
        var check_stat= localStorage.getItem('checkit-the-item');
        check_stat === '1' ? $('#checkit').prop('checked',true):$('#checkit').prop('checked',false);
        }
    }

Suggestion please!

1
  • 1
    Take off the () on your load binding. It should be $(window).load(set_func_o); so you are giving it a function reference, not invoking it immediately. Commented Dec 13, 2017 at 18:10

1 Answer 1

1

You are referencing a wrong element ID. Also, you can clean your code to only one prop setter.

function try_it(){
    var check_stat = localStorage.getItem('checkit-the-item');
    $('#check-it').prop('checked', check_stat === '1');
}
Sign up to request clarification or add additional context in comments.

3 Comments

Exactly. I've tried his code and the only thing preventing it from working was the wrong id.
How stupid I am :D . Thanks @F.Almeida for the clean code,it is much better.
I made a jquery extension that could be useful for you. Check it out jsfiddle.net/42gh5q27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.