jQuery remove checkbox and associated label
Asked Answered
R

2

7

I have the following:

<input type="checkbox" class="oDiv" id="Parent"  name="divcorp[]" value="Parent"/>
<label for="Parent">Parent</label>

I can remove the checkbox using the following, which works correctly:

$( "#Parent" ).remove();

However, how could I also remove the associated label for this checkbox?

Resnatron answered 13/12, 2013 at 14:57 Comment(0)
T
16

You can use attribute equal selector

Live Demo

$('label[for=Parent]').remove();

Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.

Tamikatamiko answered 13/12, 2013 at 14:58 Comment(4)
Given that labels are the only elements with the for attribute (or htmlFor property), you might as well specify the label in the selector, and avoid the implied universal selector (just to cut down on the work that has to be done to find the element).Bookstall
That's great - thanks - as an aside, is it possible to remove them based on where they are? - using equals, such as :eq(6)Resnatron
$('label[for="Parent"]').remove(); "" missingTheatrics
Thanks, these are not really required in this particular case. Try it without double quotesTamikatamiko
I
1

If the id of element is not known, but its value is known and the id of its parent is known, the following can be done

Code (Demo):

<div id="payment">
    <input id="RANDOM_GENERATED-1" type="checkbox" name="div[]" value="0" />
    <label for="RANDOM_GENERATED-1">Pay Now by CC</label><br/>

    <input id="RANDOM_GENERATED-2" type="checkbox" name="div[]" value="1" />
    <label for="RANDOM_GENERATED-2">Pay Now by PayPal</label><br/>

    <input id="RANDOM_GENERATED-3" type="checkbox" name="divo[]" value="2" />
    <label for="RANDOM_GENERATED-3">Pay Later by Check</label><br/>

    <input id="RANDOM_GENERATED-4" type="checkbox" name="divo[]" value="2"/>
    <label for="RANDOM_GENERATED-4">Pay Later by Cash</label><br/>
</div>

And now if one wanted to remove all the pay later elements (along with label elements), the ones with value 2

$('#payment').find("input[value=2]").each(function () {
    $(this).remove();
    $('label[for=' + $(this).attr('id') + ']').remove();
});
Izmir answered 11/9, 2016 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.