I have a simple page with 2 buttons which each populate the content of a modal remotely using the following method code
$("button").click( function(e) {
e.preventDefault();
var remoteLoc = $(this).attr('data-loc');
$("#myModal .modal-content").load(remoteLoc, function() {
$("#myModal").modal("show");
});
});
$('#myModal').on('hidden.bs.modal', function (e) {
$("#myModal .modal-content").empty();
});
A simple example of the content being loaded is this:
<div class="modal-body">
<a id="tomtest" href="#">Test link</a>
<p>dfghdfgh dfgh dfgh dfgh dfgh dfgh dfgh dfg h</p>
</div>
<script type="text/javascript">
$(document).on("click", "a#tomtest", function(e) {
e.preventDefault();
alert(123);
});
</script>
The problem is that the alert fires as many times as I've opened the modal since the page loaded.
What can I do to stop this happening?
EDIT!!!
Based on the answer from @paulitto I've amended the code to add a dynamically created link in the modal content.
<div class="modal-body">
<a id="tomAdder" href="#">Add alert link</a>
<p>dfghdfgh dfgh dfgh dfgh dfgh dfgh dfgh dfg h</p>
</div>
<script type="text/javascript">
$("a#tomAdder").on("click", function(e) {
e.preventDefault();
$('<a class="tomtest" href="#">Test link</a>').prependTo(".modal-body");
});
$(document).on("click","a.tomtest", function(e) {
e.preventDefault();
alert(123);
});
</script>
Any ideas in this case?