I have a php loop of users that opens a modal for each one individually. The problem is that nothing happens when "choices" is changed. I want to display its own fields in relation_fields for each modal separately by changing "choices". Each of the select tags are created with the select2 library, which also does not work.
<?php foreach ( $users as $user ): ?>
<div class="modal fade" id="test-<?php echo $user->id ?>" data-bs-backdrop="static" data-bs-keyboard="false"
tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-xl">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="staticBackdropLabel">modal</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form method="post" id="new_test<?php echo $user->id ?>" class="new_test_modal">
<div class="row mb-3">
<div class="col-lg-6 col-md-6 col-sm-12">
<select class="form-select" id="choices">
<option value="">numbers</option>
<option value="one">01</option>
<option value="two">02</option>
<option value="three">03</option>
</select>
</div>
<div class="col-lg-6 col-md-6 col-sm-12 relation_fields" style="display: none">
<div class="col-12" id="one_search" style="display: none">
<select name="one_search_list" id="one_search_list" class="form-control"></select>
</div>
<div class="col-12" id="two_search" style="display: none">
<select name="two_search_list" id="two_search_list" class="form-control"></select>
</div>
<div class="col-12" id="three_search" style="display: none">
<select name="three_search_list" id="three_search_list"
class="form-control"></select>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<script>
$(document).ready(function () {
$('#choices').on('change', function (e) {
e.preventDefault();
const relatedOption = $('#choices option:selected').val();
if (relatedOption !== '') {
$('.relation_fields').slideDown();
} else {
$('.relation_fields').slideUp();
}
if (relatedOption === 'one') {
$('#one_search').css('display', 'block');
} else {
$('#one_search').css('display', 'none');
}
if (relatedOption === 'two') {
$('#two_search').css('display', 'block')
} else {
$('#two_search').css('display', 'none')
}
if (relatedOption === 'three') {
$('#three_search').css('display', 'block');
} else {
$('#three_search').css('display', 'none');
}
});
}).change();
</script>
Run jquery separately modal in php loop
<select class="form-select" id="choices">is inside a loop....ids are not unique. Since you're generating modals within aforeachloop, you're repeating theidvalue for multiple elements -#statickBackdropLabel,#choices,#one_search,#one_search_list, etc. Since you're using both Bootstrap and jQuery, consider making an external modal - place your HTML and jQuery logic there, and open the modal from another file / page. For example, like this.