0

I am working on a website, which loads a left-hand menu, via a partial view (.cshtml). This menu contains a bunch of checkboxes, which are then used to toggle the visibility of map layers using the OpenLayers API. Event handlers for each checkbox are applied once the page has loaded, using some client-side JS as follows:

function buildLayerControls() {
    $(".menu-control :checkbox").on("click", function () {

        var controlValue = $(this).val();
        var isChecked = $(this).is(":checked");

        toggleControlLayerVisibility(controlValue, isChecked);

    });
};

This setup works fine if the menu remains static, but I am working on a feature that requires a portion of the menu to be updated without refreshing the page.

For example, 3rd party layers can be added to the map and subsequently need a respective checkbox to toggle the visibility. What would be the best approach to ensure the event handler above gets applied to newly created checkboxes?

For more context, the menu section I'm working on refreshes by fetching a new ViewComponent once a new layer has been added to the backend database - something similar to:

function refreshMenuSection() {
    $.ajax({
        url: "/controller/menusection",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        success: function (result) {
            $("#third-party-layers").html(result);
        }
    });
}
Duncan
  • 19
  • 4
  • Event delegation would probably be the best approach, since elements are dynamically created. Assuming the `.menu-control` part is static and it's just the checkboxes that are dynamic: `$(".menu-control").on("click", ":checkbox", function () {`. See the [`on` documentation](https://api.jquery.com/on/) (and the linked question's answers) for details. If the `.menu-control` part is also dynamic, pick a container that isn't dynamic (`body` if nothing else), and use that instead: `$(document.body).on("click", ".menu-control :checkbox", function () {`. – T.J. Crowder Sep 01 '21 at 10:40

0 Answers0