vendredi 20 novembre 2020

How to trigger an OnClick event with persistent checkboxes through refresh

I have a flight sim tracking map with a table that has some checkboxes for displaying flight plan, gps, and route. The checkboxes when click trigger an onclick event that adds or removes layers from the leaflet map to display that data. The map auto refreshes every 2 minutes and I'm trying to see if I can make any boxes a visitor checks to remain checked through that refresh.

I followed this page here on how to get the checkboxes state to persist through a pageload, and that is working great. However it doesn't trigger the onlick event so while the checkbox reloads checked, the path layers aren't turned on.

this is an example of one of the checkboxes that would turn on the Route Path. $num is an incrementing number for each row in the table.

<input id=\"RT".$num."\" type=\"checkbox\" onClick=\"markerOnCheckBoxRT$num(this)\"/>

Here's the function it triggers when checked on/off:

function markerOnCheckBoxRT<? echo $num ?>(checkboxElem) {
  if (checkboxElem.checked) {
    polyline<? echo $num ?>a.addTo(map);
    arr<? echo $num ?>.addTo(map);
    dep<? echo $num ?>.addTo(map);
  } else {
    polyline<? echo $num ?>a.removeFrom(map);
    arr<? echo $num ?>.removeFrom(map);
    dep<? echo $num ?>.removeFrom(map);
  }
}

And here's the script at the bottom of the page:

<script>
var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
    $checkboxes = $("#checkbox-container :checkbox");

$checkboxes.on("change", function(){
  $checkboxes.each(function(){
    checkboxValues[this.id] = this.checked;
  });
  
  localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});

// On page load
$.each(checkboxValues, function(key, value) {
  $("#" + key).prop('checked', value);
});
</script>

I tried doing

$("#" + key).prop('checked', value).click();

while this does trigger the onclick to show the path, it also checks and triggers every checkbox on the page, not just this single one. I tried .change() but that broke it where checks didn't persist.

Any suggestions would be greatly appreciated. thanks!




Aucun commentaire:

Enregistrer un commentaire