0

I want to make the following anchor link executable on click.

<a href="#" id="chck` + i + `" class="btn btn-primary">Check Suppliers</a>

I'm working on Javascript and Ajax to make a dynamic web page. The page fetches JSON data from a 'data.JSON' file. Below here is the part of Javascript:

        var htmlString = ``;
        var peopleString = ``;
        var b = 0;
        for (var i = 0; i < data.length; i++) {
        for (var a = 0; a < data[i].People.length; a++) {
            peopleString += `<p class="card-title"> Name: <strong>` + data[i].People[a].Name + `</strong>
        and Contact No. : <strong>` + data[i].People[a].Contact + `</strong></p>`;
    }
    htmlString +=
        `<div class="card">
            <div class="card-body">
                <h4 class="card-title"> Area: ` + data[i].Area + `</h4>
                <div class="fd" id="card-para` + i + `">` + peopleString +
              `</div><a href="#" id="check` + i + `" class="btn btn-primary">Check Suppliers</a>
            </div>
        </div>
        <script>
            var h = document.getElementById("chck` + i + `");
            h.addEventListener("click", function () {
                document.getElementById("card-para` + i + `").style.display = "block";
                document.getElementById("check` + i + `").style.display = "none";
            });
        </script>`;
    peopleString = ``;
}

On line:14, you see there is an anchor tag. When this link is clicked I want the below script tag from line:17 to line:23 (which is within the "htmlString" string variable) to be executed. The div element on line:13 has a default display: none; css property, my expected output is to make this div element of line:13 to be shown on screen i.e. it should have display: block; css property. I'm well aware that this script tag from line:17 to line:23, cannot be executed as it is inside of a string variable. Thus I'm asking for help to find a possible way no matter how, to get my expected result.

  • I suggest using [event delegation](https://stackoverflow.com/questions/1687296/what-is-dom-event-delegation) to bind the listener to a class. That way you only need to bind it once and it can be outside of the string concatenation. Is it possible to include a sample dataset? – showdev May 03 '21 at 23:04

0 Answers0