Loading JS file with HTML content to a div via ajax, if I load it multiple times the JS functions inside the test.js file runs multiple times like the content is loaded.
Creating the HTML content with PHP:
$html = '
<script src="js/test.js" charset="utf-8"></script>
<div id="form-container" class="p-3">
<label>Teszt</label>
<select class="form-control" id="type" name="type">
<option value="t1">type 1</option>
<option value="t2">type 2</option>
</select>
</div>
';
After the content is created, it sends back to the ajax and adds the content to the div.
Inside the test.js file there is event handlers like:
$(document).on("change", '#type', function (event) {
alert("test");
});
I tried to add a .js file version with PHP DateTime, but it’s not working.
2
Answers
Found the solution, with the multiple ajax load it delegate the event handlers multiple times.
To avoid it, need to remove the event handler before delegate it again.
You could do something like below: