Unsurprisingly, the
change
event fires
when the selected value is changed. It
does not fire when the page first loads.
You can either manually trigger the
change
event when the page loads:
$('#programid').change(function() {
...
}).trigger("change");
.trigger() | jQuery API Documentation[
^]
Or you can extract the handler into its own function, and explicitly call it when the page loads:
$(function(){
let selectedCourseId = null;
<?php if($row['courseid'] != null && !empty($row['courseid'])) { ?> selectedCourseId = <?php echo $row['courseid']; } ?>
const updateCourses = function(){
const semesterid = $('#semesterid').val();
const programid = $(this).val();
const courseId = selectedCourseId;
$.ajax({
...
});
};
$('#semesterid').change(updateCourses);
$('#programid').change(updateCourses);
updateCourses();
});
This approach allows you to attach the same handler to multiple events across multiple elements - for example, in this case, the
change
event on the semester list.