Reputation: 87
I have a number of inputs on my page, all of which conform to the following pattern:
<label>
<input onchange="checkvals()" name="Segment_" value="OL" id="Segment_8" type="checkbox">
Ocean Line (<span id="ms9" class="detect">0</span>)</label>
So label, input, span with a class of "detect" within it, and a value within that span.
I trying to make it so if the item class value of "detect" = 0, it sets the previous input to disabled (and conversely, if greater than zero, makes sure it's enabled).
My jQuery syntax is wrong on the selector/parent . What ought the correct syntax be?
$('.detect').each(function () {
if ($(this).text() == '0') {
$(this).closest('input').prop('disabled', 'true');
}
});
Upvotes: 0
Views: 110
Reputation: 11328
$(this).prev('input').prop('disabled', 'true');
This should work, too.
Get the immediately preceding sibling of each element in the set of matched elements.
Upvotes: 0
Reputation: 195992
.closest
finds ancestor elements, and since the span
is not inside the input
it does not work.
Description: For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
You can, however, find the label
and then locate the input
$('.detect').each(function () {
if ($(this).text() == '0') {
$(this).closest('label').find('input').prop('disabled', 'true');
}
});
Upvotes: 1
Reputation: 207501
closest looks at itself and the parents. It does not look at siblings.
$(this).closest("label").find('input').prop()
or
$(".detect").siblings("input").prop()
Upvotes: 0