1

I have a function which loops through multiple table cells and checks their values against either a text box or a select box's selected value. I have an issue where if I reach a certain point in the IF statement, I would like to break out of the each loop but I'm not sure how to do this. I looked into using labels, but I don't think they work with each statements and I don't think I can use the break; line either.

JQuery:

function CheckIfPermissionExists(IsEditRole, IsPreviousPermission, DynamicElementToAdd) {
        var count = 0;
        $('.PermissionName').each(function () {
            if (IsPreviousPermission == true) {
                var PermissionNameToAdd = $('#PermissionNameSelectBox').find(":selected").val();
                if ($(this).text() == PermissionNameToAdd) {
                    $('#CreateErrorMessage').text("Please choose a different permission as this one already exists");
                    $('#CreateErrorMessage').css("display", "block");
//Break out of each here
                    return false;
                }

                else if (count < 1) {
                    AddIntoCreateTable(IsEditRole, IsPreviousPermission, DynamicElementToAdd);
                    count++;
                }
            }
            else {
                var PermissionNameToAdd = $('#PermissionNameTextBox').val();
                if ($(this).text() == PermissionNameToAdd) {
                    $('#CreateErrorMessage').text("Please choose a different permission as this one already exists");
                    $('#CreateErrorMessage').css("display", "block");
                    return false;
//Break out of each here
                }
                else if (count < 1) {
                    AddIntoCreateTable(IsEditRole, IsPreviousPermission, DynamicElementToAdd);
                    count++;
                }
            }
        });
    }
Andrew Kilburn
  • 2,251
  • 6
  • 33
  • 65

2 Answers2

4

break; is something you can do in a while (...) or for (...) loop, but you're inside a function. The proper way to exit a function is to use return.

If you want the .each() loop to stop immediately, you should return false.

Source

Delgan
  • 18,571
  • 11
  • 90
  • 141
0

To break a $.each loop, you have to return false in the loop callback.

Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to break out of jQuery each Loop

Community
  • 1
  • 1
Daniel PurPur
  • 519
  • 3
  • 13