Home > Software engineering >  jQuery each() loop does not return control when a condition is met
jQuery each() loop does not return control when a condition is met

Time:12-12

I want return true/false from my function when the if condition is met. However it's not returning true, every time it returns false. Please help me. Thanks.

function catExists(cName) {
  $("#room_has_cat_table tbody tr td:first-child").each(function(index, item) {
    var existingCat = $(this).text();
    alert(existingCat);
    
    if (existingCat == cName) {
      return true;
    }
  });
  
  return false;
}

CodePudding user response:

The problem with your logic is because you cannot return a value from an anonymous function.

To correct your logic define a boolean variable which you can update inside the loop when a match is found:

function foo(cName) {
  let matchFound = false;

  $("#room_has_cat_table tbody tr td:first-child").each(function() {
    var existingCat = $(this).text();
    if (existingCat == cName) {
      matchFound = true;
      return; // exit the each() loop
    }
  });

  return matchFound;
}

However, a better approach entirely would be to use filter() to find the match. This avoids the need for the explicit loop:

let matchFound = $("#room_has_cat_table tbody tr td:first-child").filter((i, el) => el.innerText.trim() === cName).length !== 0;
  • Related