samedi 22 septembre 2018

Saving multiple checkbox values and a check all checkbox value with localstorage

I have set up localstorage to save the value of my checkboxes and have a "check all" and "uncheck all" function. I am trying to implement a way to show only the checked items when a specific checkbox, separate from the "check all" group of checkboxes, is checked. The problem I am having is saving that checkbox value into localstorage. I see in the console that my formValues checkboxes as well as my separate showHide checkbox are saved in localstorage. I am just getting stumped at the show and hide functionality working with the check all functionality. I realize this may be confusing. Any help or direction is appreciated!

Here is a codepen

var formValues = JSON.parse(localStorage.getItem("formValues")) || {};
var showHide = JSON.parse(localStorage.getItem("showHide")) || {};
var $checkboxes = $("#checkbox-container input.drug");
var $button = $("#checkbox-container .checkall");
var $show = $("#checkbox-container #hideDrugs");

if ($show.prop('checked', true)) {
  $('.Rtable-row.hidden-print').fadeOut(200);
} else {
  $('.Rtable-row.hidden-print').fadeIn(200);
}
$show.on("change", function() {
  if (this.checked) {
    $('.Rtable-row.hidden-print').fadeOut(200);
  } else {
    $('.Rtable-row.hidden-print').fadeIn(200);
  }
});

function allChecked() {
  return $checkboxes.length === $checkboxes.filter(":checked").length;
}

function updateButtonStatus() {
  $button.text(allChecked() ? "Uncheck all" : "Check all");
  $button.filter(function() {
    if ($(this).text() == 'Check all') {
      $show.prop('checked', false);
    } else {}
  })
}

function handleButtonClick() {
  $checkboxes.prop("checked", allChecked() ? false : true);
}

function updateStorage() {
  $checkboxes.each(function() {
    formValues[this.id] = this.checked;
    if (this.checked) {
      $(this).parents('.Rtable-row').removeClass('hidden-print');
    } else {
      $(this).parents('.Rtable-row').addClass('hidden-print');
    }
  });
  $show.each(function() {
    showHide = this.checked;
    if (this.checked) {
      console.log('checked')
    } else {
      console.log('unchecked')
    }
  });

  formValues["buttonText"] = $button.text();
  localStorage.setItem("formValues", JSON.stringify(formValues));
  localStorage.setItem("showHide", JSON.stringify(showHide));
}

$button.on("click", function() {
  handleButtonClick();
  updateButtonStatus();
  updateStorage();
});

$show.on("change", function() {
  updateStorage();
});
$checkboxes.on("change", function() {
  updateButtonStatus();
  updateStorage();
});

// On page load
$.each(formValues, function(key, value) {
  $("#" + key).prop("checked", value);
});
$show.prop('checked', showHide.value);
$button.text(formValues["buttonText"]);



Aucun commentaire:

Enregistrer un commentaire