user7355700
user7355700

Reputation: 87

JQuery Set Property of Input(s) based upon Class Value

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

Answers (3)

sinisake
sinisake

Reputation: 11328

 $(this).prev('input').prop('disabled', 'true');

This should work, too.

https://api.jquery.com/prev/

Get the immediately preceding sibling of each element in the set of matched elements.

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195992

.closest finds ancestor elements, and since the span is not inside the input it does not work.

Quote from the .closest docs

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

epascarello
epascarello

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

Related Questions