0

I want to do this : - When I click the checkbox "div=true" or "div=flase", will be shown or hidden - Status of checkbox to be saved and with this, even the last method called to be saved

Problem - Status of checkbox is saved at refresh of page, but the last method called is not saved.

I do not understand where is my mistake.

Here is the code:

<input type='checkbox' id='LineOp' />  Show/Hide Weekends
<div id="true">
    <p>Hide weekend</p>
</div>
<div id="false">
    <p>Show weekend</p>
</div>



function SaveLastCheck() {
    var getStstus = localStorage.getItem("LineOp");

    if (getStstus === "true")
        $("#LineOp").prop("checked", true);

    $("#LineOp").click(function(){
        localStorage.setItem('LineOp', $(this).prop("checked"));
    });

}

$(document).ready(function() {
    SaveLastCheck();
});

$(document).ready(function show_weekends () {
    var checkbox = $('#LineOp'); 
    var dependent = $('#true');
    if (checkbox.attr('checked') !== undefined){
      dependent.show();

    } else {
        dependent.hide();

    }

    checkbox.change(function(e){
       dependent.toggle(); 
    });
});


$(document).ready(function hide_weekends () {
    var checkbox = $('#LineOp'); 
    var dependent = $('#false');
    if (checkbox.attr('checked') == undefined){
      dependent.show();

    } else {
        dependent.hide();

    }

    checkbox.change(function(e){
       dependent.toggle(); 
    });
});

HERE IS MY EXAMPLE http://jsfiddle.net/b3g6arbd/4/

Nazaf Anwar
  • 339
  • 1
  • 8
  • 17
Silviu
  • 175
  • 5
  • 15
  • possible duplicate of [checkbox checked with prop() does not fire events attached to "change"](http://stackoverflow.com/questions/19505011/checkbox-checked-with-prop-does-not-fire-events-attached-to-change) – Kevin Grabher Mar 23 '15 at 11:04

1 Answers1

0

It will work if you use jQuery's is() for checking the initial state and you can shorten your code by passing the checkbox state to toggle. Then you won't need to duplicate your code.

E.g.:

$(document).ready(function() {
    SaveLastCheck();

    var checkbox = $('#LineOp'); 
    $('#true').toggle(checkbox.is(':checked'));
    $('#false').toggle(!checkbox.is(':checked'));
    checkbox .change(function () {
        $('#true').toggle(this.checked);
        $('#false').toggle(!this.checked);
    });
});

Here is the updated example: http://jsfiddle.net/b3g6arbd/12/

Also see this question and the answers for more examples on checking a checkbox' state.

Community
  • 1
  • 1
Baris Akar
  • 4,895
  • 1
  • 26
  • 54
  • @Silviu : Please mark the answer as accepted then (checkmark next to the answer) and since you are a new user, please take the tour to learn how to use stackoverflow: http://stackoverflow.com/tour – Baris Akar Mar 23 '15 at 13:23