简体   繁体   中英

Toggle div and set cookie to save jQuery

I use the following code to toggle a specific div and save the setting with a cookie, so that it wil keep the change.

But for some reason the save cookie section is not working well. It seems that the cookie is not saved when using the previous browser buttons for example.

What am I missing in my current code the perfectly add a cookie and check it.

function getCookieValue(a) {
  var b = document.cookie.match('(^|;)\\s*' + a + '\\s*=\\s*([^;]+)');
  return b ? b.pop() : '';
}

$(document).ready(function() {

  var redEl = $('input#togglebtw');

  if (document.cookie.indexOf('togglebtw=') != -1) {
    redEl.prop("checked", $.parseJSON(getCookieValue("togglebtw")));
  }

  if (redEl.prop("checked")) {
    $(".price-container .price-including-tax").hide();
    $(".price-container .price-excluding-tax").show();
  } else {
    $(".price-container .price-excluding-tax").hide();
    $(".price-container .price-including-tax").show();
  }

  $('input#togglebtw').click(function() {

    var expiryDate = new Date();
    expiryDate.setDate(expiryDate.getDate() + 31);
    expiryDate = expiryDate.toUTCString();

    if ($(this).attr("class") == "btwToggler") {
      if (redEl.prop("checked")) {
        $(".price-container .price-including-tax").hide();
        $(".price-container .price-excluding-tax").show();
      } else {
        $(".price-container .price-excluding-tax").hide();
        $(".price-container .price-including-tax").show();
      }
      document.cookie = "togglebtw=" + this.checked.toString() + "; expires=" + expiryDate;
    }
  });
});
<input id="togglebtw" class="btwToggler" type="checkbox">

Use local or sessionStorage, then you do not need to worry about the cookie is correct or not

Try this simplified version

const checkBTW = function() {
  const checked = $('#togglebtw').is(":checked");
  $(".price-container .price-including-tax").toggle(!checked);
  $(".price-container .price-excluding-tax").toggle(checked);
  localStorage.setItem("togglebtw",checked?"true":"false");
};
$(function() {
  $('#togglebtw')
    .on("click",checkBTW)
    .prop("checked",localStorage.getItem("togglebtw")==="true"); 
  checkBTW();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM