I'm looping through all entries from database and using an if condition to check if the departmentID matches to my given ID. Problem is when the If condition is true it also runs the else condition but when the condition is false it only runs the else part which is fine.
$.ajax({
url: "php/getall.php",
type: 'GET',
dataType: 'json',
success: function(result) {
employees = result['data'];
console.log(employees);
employees.forEach((employee) => {
if (employee.departmentID === deptid) {
$('#preventdel').modal('show');
} else {
$('#confirmdel').modal('show');
}
})
}
})
It shows both modals if the condition is true but if the condition is not met it works fine
If and else both executing want to exit the loop if the condition is met at once
CodePudding user response:
You are executing your code inside a loop, so there should be as many modals as there are elements in the employee, because You are using if-else statement. So one of those two blocks of code will execute for each element.
const hasEmployee = employees.some(employee => employee.departmentID === deptid);
if (hasEmployee) {
$('#preventdel').modal('show');
} else {
$('#confirmdel').modal('show');
}
By using some() method, You can check if your searched elements exists in your results. Then open your modal only once at the end.