Storing checkbox value in local storage

2019-02-15 14:09发布

问题:

I have a checkbox whose value $row['uid'] I would like to store in local storage using javascript or jquery. When the user "unchecks" the checkbox, the value should be removed from local storage

This is my html:

<form> Favorites <input type="checkbox" class="favorite" value="'.$row['uid'].' onclick='.fave.add();'"></form>

This is what I have for the local storage in javascript at the moment. I'm not quite sure how I should add and remove the value $row['uid']

    var fave = fave || {};
    var data = JSON.parse(localStorage.getItem("favorite"));
    data = data || {};
            var fave = fave || {};
            var data = JSON.parse(localStorage.getItem("favorite"));
            data = data || {};
            $(function () {
                var data = localStorage.getItem("favorite");

                if (data !== null) {
                    $("input[name='favorites']").attr("checked", "checked");
                }
            });
            $("input[name='favorites']").click(function () {
                if ($(this).is(":checked")) {
                localStorage.setItem("favorite", $(this).val());
                } 
                else {
                    localStorage.removeItem("favorite");
                }
            });

Any and all help is much appreciated!

回答1:

localStorage has two main functions, getItem and setItem. For setItem you pass in a key and a value. If you write to that key again, it will rewrite that value. So in your case, if a box is checked you would do localStorage.setItem("checkbox_value", true) and when it is unchecked you would pass in false instead. To get the value you can look at using jQuery like so: $(checkbox).is(':checked') and use a simple if-else clause to pass in true or false. then when you reload your page, on $( document ).ready() you can get the values using localStorage.getItem(key) and use Javascript to set the check boxes values.

This is how i would go about using localStorage to remember check box values.

Hope i helped! Ask me if anything is unclear.



回答2:

Here's an example to get you headed in the right direction:

var boxes, arr;

// This function loads the array and then checks the uid of each checkbox
// against it.

function checkBoxes() {
  arr = loadBoxArray();
  $.each($('input[type=checkbox]'), function (i, el) {
    if (arr.indexOf(i) > -1) {
      $(this).prop('checked', true);
    } else {
      $(this).prop('checked', false);
    }
  });
}

// If the localStorage item is available, load it into an array
// otherwise set a default array and save it to localStorage

function loadBoxArray() {
  if (localStorage.getItem('boxes')) {
    arr = loadBoxArray();
  } else {
    arr = [0, 2];
    saveBoxArray(arr);
  }
}

// Save the array to localStorage    

function saveBoxArray(arr) {
  localStorage.setItem('boxes', JSON.stringify(arr));
}

// On page load check the boxes found in localStorage

checkBoxes();

// Clicking a checkbox will update the checkbox array which is then saved to localStorage

$('input[type=checkbox]').click(function () {
  var arr = $.map($('input[type=checkbox]:checked'), function (el) {
    return $(el).data('uid');
  });
  saveBoxArray(arr);
});


回答3:

If you want the check box state to persist after page refresh and if you don't mind using jQuery:

http://jsfiddle.net/9L2Ac/

$(function () {
    var data = localStorage.getItem("favorite");

    if (data !== null) {
        $("input[name='favorites']").attr("checked", "checked");
    }


});



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

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

});