简体   繁体   中英

If and else both statement executing

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM