I'm trying to build a function using the .each() method in jQuery that scans for empty input fields, highlights them in red, and then provides an alert message to let the user know what needs to change.
Here's my sample html:
<tr>
<td><input type="number" class="amount required" name="amount" ></td>
<td><input type="number" class="carrier required" name="carrier" ></td>
<td><input type="number" class="kilo required" name="kilo" ></td>
</tr>
<button type="submit" class="analyze">Analyze</button>
Here's the function to loop through the table data and add the CSS:
$(".analyze").click(function() {
$(".required").each(function() {
if ($(this).val() === "") {
$(this).parents("td").addClass("redClass");
alert("Looks like some of the fields aren't filled out correctly. They're highlighted in red.");
}
});
});
The issue is that the code goes through the array one-by-one and creates an alert message for every single empty cell. Ideally it'd add .redClass to the empty fields all at once and just present one alert message at the end if any are empty.