简体   繁体   中英

Selecting child of adjacent parent elements in Jquery

Right now I have aa bootstrap row set up with a checkbox and input inside of it.

<div class="row">
<div class="AdminFees">
    <div class="col-md-2"><input type="checkbox" class="make-switch feeswitch" data-on-color="info" data-off-color="info" data-on-text="Yes" data-off-text="No" name="HasPerMemberFee" checked="@Model.Contract.HasPerMemberFee" /></div>
</div>
<div class="col-md-2"><input type="text" class="form-control" placeholder="$0.00" id="PerMemberFeeAmount" name="PerMemberFeeAmount" value="@Model.Contract.PerMemberFeeAmount" /></div>

I have 6 or 7 very identical field pairs that I am manipulating generically so I don't have to make multiple functions. I am having trouble figuring out how to reference the text input element from the checkbox element.

Jquery:

$('.feeswitch').each(function () {
    $(this).on('switchChange.bootstrapSwitch', function () {
        if ($(this).bootstrapSwitch('state') == true)
            $(this).next('input').css('visibility', 'visible');
        else
            $(this).next('input').css('visibility', 'hidden');
    });
});

I have tried next and nextAll, but to my understanding, those only find child elements. I need to know how to select the child of the second adjacent parent element.

In an attempt to simplify the situation:

The checkbox has 2 parents, the two divs, and 1 adjacent element, the other div column. I need to access the child of that other div column, but it needs to be generically so I don't need to make 8 functions for each checkbox/input pair on my page.

I'm not sure I agree that the accepted solutions is stable, since it's selector greatly depends on keeping your structure the same, which I would suggest is unlikely in most projects. If I might suggest an alternative, I think the better method here is to employ the scope parameter of the selector.

$('.feeswitch').on('switchChange.bootstrapSwitch', function () {
    var switchState = $(this).bootstrapSwitch('state') ? "visible" : "hidden";
    $('input',$(this).closest('.row')).not($(this)).css('visibility', switchState);
});

Regardless, you should definitely look more in to jQuery DOM traversal methods, as that's pretty much the big magic of jQuery:

https://api.jquery.com/category/traversing/

You'll want to say something like:

$(this).parent().parent().next('div').find('input').
  css('visibility', 'visible');

And since this is generic, you don't need the each() :

$('.feeswitch').on('switchChange.bootstrapSwitch', 
  function () {
    var visi = $(this).bootstrapSwitch('state') ? 'visible' : 'hidden';

    $(this).parent().parent().next('div').find('input').
      css('visibility', visi);
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM