Background Swap:

How to save a single check checkbox after page refresh?

HTML code:

    <div class="wrap">
        <h3>Background Swap:</h3>
        <form action="" method="POST">
            <div id="checkbox-container">
                Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />
            </div>
            <input type="submit" name="submit" value="Upgrade Background" class="button" />
        </form>
    </div>

This will check the check box, but when the page refreshes or exits and returns, the check box will be unchecked. So after some research, I tried localStorage, but it seems I haven't figured it out yet.

localStorage code:

    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {};
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function(){
        $checkbox.each(function(){
            checkboxValue[this.id] = this.checked; 
        });
        localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value){
        $("#" + key).prop('checked', value);
    });

I have script tags around localStorage code and after implementing these codes my checkbox is still not checked.

Both codes in general:

<div class="wrap">
<h3>Background Swap:</h3>
<form action="" method="POST">
    <div id="checkbox-container">
        Background Swap: <input type="checkbox" name="new_background"/>
    </div>
    <script>
        var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
        var $checkbox = $("#checkbox-container :checkbox");

        $checkbox.on("change", function(){
            $checkbox.each(function(){
                checkboxValue[this.id] = this.checked; 
            });
            localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
        });

        //on page load
        $.each(checkboxValue, function(key, value){
            $("#" + key).prop('checked', value);
        });
        </script>
        <input type="submit" name="submit" value="Upgrade Background" class="button"/>
</form>
</div>

I would like to thank everyone who took the time to help me sort out the solution to my question with the biggest thanks @Pranav C Balan !!! Check out the finished code @ stack overflow

+6
source share
6

, , , . , $("#checkbox-container :checkbox") , DOM.

, , id, , , JSON id.

<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>
  <script>
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  </script>
</div>

: FIDDLE


<script>
  // document ready handler
  // or $(document).ready(Function(){...
  jQuery(function($) {
    var checkboxValue = JSON.parse(localStorage.getItem('checkboxValue')) || {}
    var $checkbox = $("#checkbox-container :checkbox");

    $checkbox.on("change", function() {
      $checkbox.each(function() {
        checkboxValue[this.id] = this.checked;
      });
      localStorage.setItem("checkboxValue", JSON.stringify(checkboxValue));
    });

    //on page load
    $.each(checkboxValue, function(key, value) {
      $("#" + key).prop('checked', value);
    });
  });
</script>
<div class="wrap">
  <h3>Background Swap:</h3>
  <form action="" method="POST">
    <div id="checkbox-container">
      Background Swap: <input type="checkbox" id="name" name="new_background" />
    </div>

    <input type="submit" name="submit" value="Upgrade Background" class="button" />
  </form>

</div>

: FIDDLE

+1

localStorage, document.cookie:

$('input:checkbox').change(function() {
    saveCookies();
});

:

function saveCookies() {
    var checkArray = [];
    $('input.comic-check').each(function() {
        if ($(this).is(':checked')) {
            checkArray.push(1);
        } else {
            checkArray.push(0);
        }
    });
    document.cookie = "checks=" + checkArray;
}

localStorage , ,

( )

var checks = getCookie("checks");
if (checks != "") {
    checkArray = checks.split(',');
    //unchecks boxes based on cookies
    //also has backwards compatability provided we only append to the list in landing.ejs/generator.js
    for (var i = 0; i < checkArray.length; i++) {
        if (checkArray[i] == "0" && $('input.comic-check').length > i) {
            var checkBox = $('input.comic-check')[i];
            $(checkBox).prop('checked', false);
        }
    }
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
0

:

<?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>

<?php echo (isset($_POST['new_background']) && $_POST['new_background']=="on")? "checked" : "";?>

HTML checked checked=checked.
checked .

checked=checked JavaScript .


...

CodePen

//on page load, check the appropriate checkboxes.
var onloadChecks = JSON.parse(localStorage.getItem("checkboxValue"))
$.each(onloadChecks, function(key, value){
  $("#" + key).prop('checked', value);
});

// ================ Saving checks

// Checkboxes collection.
var allCheckboxes = $("input[type='checkbox']");

// On change handler.
allCheckboxes.on("change", function() {

  // Check how many checkboxes we have.
  var jsonCheckboxes = {};
  console.log("There is "+allCheckboxes.length+" checkboxes.");

  // Building the json.
  for(i=0;i<allCheckboxes.length;i++){
    console.log(allCheckboxes.eq(i).attr("id"));
    console.log(allCheckboxes.eq(i).is(":checked"));
    jsonCheckboxes[allCheckboxes.eq(i).attr("id")] = allCheckboxes.eq(i).is(":checked");
  }
  console.log("jsonCheckboxes: "+JSON.stringify(jsonCheckboxes));

  // Setting localStorage.
  localStorage.setItem("checkboxValue", JSON.stringify(jsonCheckboxes));
  console.log("LocalStorage: "+ localStorage.getItem("checkboxValue") );
});
0

  • PHP checked="checked" ()

  • localStorage true ()

  • .

, , , , , , PHP ( php , localStorege set )

: https://jsfiddle.net/dalinhuang/efwc7ejb/

//on page load
$.each(checkboxValue, function(key, value) {
    if(value){
       $("#" + key).prop('checked', value);
    }
});
0

: my goal is to find something that will make my checkbox stays checked if the user choose to, , localStorage :

jQuery (3.2.1)

$(document).ready(function() {

var bground = localStorage.getItem('background'); // get the value if exists

if (bground == 'shadow') { // checkbox has been previously checked
    $('#checker').attr('checked', 'checked');
}
if (bground == 'shadowless') { // checkbox has been previously unchecked
    $('#checker').attr('');
}

$('#submit').submit(function() { // when form is submitted
    bground = localStorage.getItem('background'); // get the value in LS
    if($('#checker').is(':checked')) // is it checked or not ?
    { sh = 'shadow'; } else { sh = 'shadowless'; }
    localStorage.setItem('background', sh); // update LS with new value
}); 

});

HTML ( id="submit" )

<form action="" id="submit" method="POST">
  <div id="checkbox-container">
  Shadowless background: <input type="checkbox" name="new_background" id="checker" /><br />
  </div>
  <input type="submit" name="submit" value="Upgrade Background" class="button" />
</form>

, , , / .

jQuery change . :

$('#submit').submit(function() { // comment/delete this line
// to the one below
// $('#checker').change(function() { // uncomment this line
0

 Shadowless background: <input type="checkbox" name="new_background" id="checker" <?php echo (isset($_POST['new_background']))? "checked='checked'": "";?>/><br /><br />

Shadowless background: <input type="checkbox" name="new_background" id="checker" value="<?php echo (isset($_POST['new_background']))? ";?>/><br /><br />

$_POST['new_background'] 't' of 'f' .

-2

All Articles