I use jquery and ajax to open the bootstrap modal window. My code works fine when it is not in a loop, and my content is displayed accordingly in a modal window. But I have five modals on the page, and I would like to use a for loop, so I don't repeat my code five times.
It seems that there is no need to write a for loop to execute the code five times, but for some reason there is a problem, and when I put the code in the for loop, the modal content will not be displayed in the window that opens.
Here is the code that works, how I need it, so the modal content from my modal1.php file is displayed in a modal popup. Note that the variable i is used three times; once in the jquery selector and twice in the $ .ajax (...) scope:
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 i variable in exactly the same way as the code above. However, with the code below, the contents of modal1.php does not display (and does not make any other files named "modal [i] .php"). Instead, when opened, only an empty dark background appears.
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);
}
});
});
}
, $.ajax() for, jquery $('# modal' + i), , . , , ajax i? , ?
, , , , . , , . , . , , .