Note: The suggested question is not exactly a duplicate, but one of the answers in there does provide a solution.
My annotated code is as follows:
function AddMedRow(brand, generic, dose, doseunits, freq, durn, durnunit, instrn) {
$(".DrugRow").each(function () {
id = $(this).attr('id');
count = Number(id.replace("DrugRow", ""))
// If this row is empty, can add here
if ($("#brand" + count).val() == "" && $("#generic" + count).val() == "") {
$("#brand" + count).val(brand)
// I actually want to return true and break out of AddMedRow
return true
}
});
// Some other code continues here, but should not execute once the if block in .each is true
}
Edit: I checked with the following code:
function AddMedRow(brand, generic, dose, doseunits, freq, durn, durnunit, instrn) {
dontiterate = false
$(".DrugRow").each(function () {
id = $(this).attr('id');
console.log("id is " + id);
// If this row is empty, can add here
count = id.replace("DrugRow", "");
count = Number(count)
if ($("#brand" + count).val() == "" && $("#generic" + count).val() == "") {
$("#brand" + count).val(brand)
dontiterate = true
console.log("Let's see if we can break out without a control variable")
return false
}
});
if (dontiterate) {
console.log("Not iterating because we are checking a control variable.")
return true
}
}
The result:
id is DrugRow1
Let's see if we can break out without a control variable
Not iterating because we are checking a control variable.
That means returning true or false from within .each doesnt do anything. You need to use a control variable or flag