简体   繁体   中英

how to add class to div in which radio has certain value with jquery

I have this form with 4 radios:

<form class="options" method="post" id="question" action="index.php">
    <div class="form-check form-group"> 
        <label class="form-check-label">
            <input class='radio form-check-input' type='radio' name='radio' value='1' />Radio 1
        </label>
    </div>
    <div class="form-check form-group"> 
        <label class="form-check-label">
            <input class='radio form-check-input' type='radio' name='radio' value='2' />Radio 2
        </label>
    </div>
    <div class="form-check form-group"> 
        <label class="form-check-label">
            <input class='radio form-check-input' type='radio' name='radio' value='3' />Radio 3
        </label>
    </div>
    <div class="form-check form-group"> 
        <label class="form-check-label">
            <input class='radio form-check-input' type='radio' name='radio' value='4' />Radio 4
        </label>
    </div>

    <button type="submit" class="btn btn-success" name="next" value="next">NEXT</button>

</form

How can i add a class alert-success to the div above in which the radio has value 2 (with jquery)?

So:

 <div class="form-check form-group alert-success"> 
        <label class="form-check-label">
            <input class='radio form-check-input' type='radio' name='radio' value='2' />Radio 2
        </label>
    </div>

$('input[value=2]').closest('div').addClass('alert-success');

也能用。。

您可以使用:has jQuery 选择器:

$('.form-group:has(input[value=2])').addClass('alert-success');
$('input').filter('[value=2]').closest('.form-group').addClass('alert-success');

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