Why does this script add a class to every radio button and checkbox Label on the page, instead of just the ones for each individual checkbox/radio button?
For example, I have these buttons:
<input class="required" id="Example31" name="Example3" type="checkbox" />
<label for="Example31">Example Input 3 Option 1</label>
<input class="required" id="Example32" name="Example3" type="checkbox" />
<label for="Example32">Example Input 3 Option 2</label>
<input class="required" id="Example4" name="Example4" type="radio" />
<label for="Example4">Example Input 4</label>
And this script:
$("input.required").each(function() {
if ($(this + ":checkbox") || $(this + ":radio")) {
if (!$(this + ":checked").val()) {
var inputId = $(this).attr("id");
$("label[for=" + inputId + "]").addClass("error");
};
};
});
The script fires when I click a button. If no box is checked, every label gets an error added to it, which is correct. However, if one box is checked, no label gets an error on it, which is incorrect. If I check a checkbox in the first group, but leave the radio button unchecked, that radio button should be marked as an error.
NOTE: I know this script doesn’t account form the input names just yet (so if one checkbox with the same name is checked, the other would currently display an error), I’m trying to get his bug worked out before moving forward.
These lines of code are complete nonsense, they cannot do anything useful or sane:
I suspect you’re trying to do…
By way of explanation,
this + ":checkbox"will always produce a selector like[object Something]:checkbox, whereSomethingwill vary based on the value ofthis:checkboxelementswhich have the attributeswhich is almost certainly not what you want and will very likely match no elements; Actually I’m not sure why this works;objectandSomething, (see Has Attribute selector)[object]is a valid selector, and[object Something]:checkboxis a working (but likely invalid – jQuery bug?) selector but[object Something]is an invalid selector and raises an error$("...)will always produce a jQuery object with 0 or more elements, which is always truthy. Instead ofif ($(...)) {, you need to checkif ($(...).length > 0)To summarize, you’re producing an invalid selector which (through some quirk of jQuery) doesn’t raise an error, but which returns completely bogus results.