Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading