vendredi 17 septembre 2021

Updating checkbox ID's with sessionStorage

I currently have a mostly working script that compares two checkbox ID's when the compare button is pressed.

However, after using a sessionStorage script I found online, I found that now my checkbox values don't update unless I refresh the page (since sessionStorage makes it so the browser only sees the last selected value, and not the new one).

Is there any way to KEEP sessionStorage--as in, have the browser remember the last selected checkbox value--but also update the value in the checkboxes WITHOUT refreshing the page?

Much appreciated!

<input data-selector="edit-submit" type="submit" id="edit-submit" value="Search" class="button js-form-submit form-submit btn btn-primary form-control">
<input data-selector="edit-reset" type="submit" id="edit-reset" name="op" value="Reset" class="button js-form-submit form-submit btn btn-primary form-control">
<button type="button" class="btn btn-sm btn-primary" id="compare">Compare</button>
<input type="checkbox" id="td0" class="form-check-input" value="">
<input type="checkbox" id="td1" class="form-check-input" value="">
<input type="checkbox" id="td2" class="form-check-input" value="">
<input type="checkbox" id="td3" class="form-check-input" value="">
<input type="checkbox" id="td4" class="form-check-input" value="">
<input type="checkbox" id="td5" class="form-check-input" value="">
<input type="checkbox" id="td6" class="form-check-input" value="">
<input type="checkbox" id="td7" class="form-check-input" value="">

function onReady() {
    $(function(){
  $("input:checkbox").change(function(){
    var len = $("input:checkbox:checked").length;
    if(len == 0)
      $("#compare[type='button']").prop("disabled", true);
    else
      $("#compare[type='button']").removeAttr("disabled");
  });
});
   $(function(){
    $('input:checkbox').each(function() {
        var $el = $(this);
        $el.prop('checked', sessionStorage[$el.prop('id')] === 'true');
     });

    $('input:checkbox').on('change', function() {
        var $el = $(this);
        sessionStorage[$el.prop('id')] = $el.is(':checked');
   });
});

var all_checkboxes_search = jQuery(':checkbox');
jQuery('#edit-submit').on('click', function(event){
    all_checkboxes_search.prop('checked', false).change();
  });

var all_checkboxes_reset = jQuery(':checkbox');
jQuery('#edit-reset').on('click', function(event){
    all_checkboxes_reset.prop('checked', false).change();
  });

$(function() {
  $("input:checkbox").change(function(index){ 
    var limit = 4;
    if($("input:checkbox:checked").length >= limit) {
      this.checked = false;
  }
});

  var txt = $('input:checked')
  .map(function() { 
  return this.id;
  })
  .get().join(',');
 
$("#compare[type='button']").click(function() { 
    alert(txt);
   });
 });
}
$(document).ready(onReady);    



Aucun commentaire:

Enregistrer un commentaire