I'm using jQuery and ajax to open a bootstrap modal window. My code works perfectly when not in a loop, and my content is displayed appropriately in the modal window. But I have five modals on the page, and naturally I'd like to use a for loop so I don't repeat my code five times.
It seems like a no-brainer to write a for loop to execute the code five times, but somehow, there is a problem, and when I put the code into a for loop, the modal content will not show in the opened window.
Here is code that works how I need it, so the modal content from my modal1.php file shows in a modal popup window. Notice that the i
variable is used three times; once in the jQuery selector, and twice in the $.ajax(...) area:
var i = 1;
$('#modal' + i).on('show.bs.modal', function(e) {
var id = e.relatedTarget.dataset.id;
$.ajax({
type:'post',
url:'modals/modal' + i + '.php',
data:{id:id},
success:function(data){
$('#modal' + i).html(data);
}
});
});
This code below uses the variable i the exact same way as the code above. However, with the code below, the modal1.php content does not show (nor do any of the other files named 'modal[i].php'). Instead, only a blank dark background appears when they are opened.
for (i = 1; i < 6; i++) {
$('#modal' + i).on('show.bs.modal', function(e) {
var id = e.relatedTarget.dataset.id;
$.ajax({
type:'post',
url:'modals/modal' + i + '.php',
data:{id:id},
success:function(data){
$('#modal' + i).html(data);
}
});
});
}
So I don't understand why the $.ajax() area of the code won't recognize the i variable in the for condition, but it will recognize it in the initial jQuery selector $('#modal' + i), which I've tested and found to be true. Is there a way I can write this loop so that the ajax area will recognize the i variable? Or is there a mistake in my code that I'm overlooking?
Incidentally, I've noticed that similar questions have been asked, but they have been downvoted for not being clearly written. I've read them all, and they don't answer the question that I have today.