jeudi 5 septembre 2019

How to save one of tow checkbox in localstorage without a button

I have two checkboxes to choose between two payment-methods. If the form shows an error in the fields, the page reloads.

Now the first payment-method should be always selected as the first, but if the user checked and filled out the second payment-method, with an error, the page jumps always back to the first payment-method.

I tried to solve the problem with localstorage, but failed trying.

window.onload = onPageLoad();

function onPageLoad() {

  let checked = "true" == localStorage.getItem("checked");
  jQuery("#kreditkarteCheckbox").prop('checked', checked);
  if (jQuery(".kreditkarte").is(':checked')) {
    jQuery('.sepa').removeAttr('checked');
    jQuery('#kreditkarte').addClass('show');
  } else {
    jQuery('#sepa').addClass('show');
    localStorage.removeItem('checked');
    jQuery('.kreditkarte').removeAttr('checked');
    jQuery("#kreditkarteCheckbox").removeAttr('checked');
  }
}

jQuery('#kreditkarteCheckbox').click(function() {
  let checked = $("#kreditkarteCheckbox").is(":checked");
  localStorage.setItem("checked", checked);
});

jQuery('.sepa').click(function() {
      if (jQuery('#kreditkarte').hasClass('show')) {
        jQuery('#kreditkarte').removeClass('show');
      }

      if (jQuery('#kreditkarteCheckbox').is(':checked')) {
        jQuery('.kreditkarte').removeAttr('checked');
        jQuery("#kreditkarteCheckbox").removeAttr('checked');
      }
      jQuery('.kreditkarte').removeAttr('checked');
      localStorage.removeItem('checked');
      jQuery("#kreditkarteCheckbox").removeAttr('checked');
    }

    jQuery('.kreditkarte').click(function() {
        if (jQuery('#sepa').hasClass('show')) {
          jQuery('#sepa').removeClass('show');
        }
        if (jQuery('.sepa').is(':checked')) {
          jQuery('.sepa').removeAttr('checked');
        };
<input type="checkbox" class="sepa" id="SepaCheckbox" data-toggle="collapse" data-target=".collapse#sepa" data-text="Collapse" checked <input type="checkbox" class="kreditkarte" id="kreditkarteCheckbox" data-toggle="collapse" data-target=".collapse#kreditkarte"
  data-text="Collapse">



Aucun commentaire:

Enregistrer un commentaire