jQuery remove checkbox and associated label

21.5k views Asked by At

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?

2

There are 2 answers

4
Adil On BEST ANSWER

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.

0
VanagaS On

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();
});