Skip to content Skip to sidebar Skip to footer

Storing Checkbox Value In Local Storage

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

Solution 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.

Solution 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.functioncheckBoxes() {
  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 localStoragefunctionloadBoxArray() {
  if (localStorage.getItem('boxes')) {
    arr = loadBoxArray();
  } else {
    arr = [0, 2];
    saveBoxArray(arr);
  }
}

// Save the array to localStorage    functionsaveBoxArray(arr) {
  localStorage.setItem('boxes', JSON.stringify(arr));
}

// On page load check the boxes found in localStoragecheckBoxes();

// 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);
});

Post a Comment for "Storing Checkbox Value In Local Storage"