开发者

Need checkbox with label delete function in jquery

I have a set of check boxes with labels. You will check any checkbox and click delete button, that checkbox & label should be deleted.

My code will delete checkbox only, that corresponding label not deleted. I need to delete the both checkbox and label. My code is

<input type="check开发者_开发百科box" id="check1" /><label>Do you like summer?</label><br>
<input type="checkbox" id="check2" /><label>Do you like winter?</label><br>
<input type="checkbox" id="check3" /><label>Do you like both</label><br>
<input type="checkbox" id="check4" /><label>other</label><br>
<button>delete</button>

<script>

    $("button").click(function () {
     $("#"+$(":checked").remove());
    });

</script>


Those checkboxes don't have labels. A label should have the for="checkX" attribute to be linked to checkbox. If you do that, it makes it easier too, to select the label for a checkbox, because you can write a selector like this:

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

Of course you van find the label, as demonstrated in Nicola Peluchetti's answer, but it's better to give the label a 'for' attribute. It improves accessability to your website too. It is actually the purpose of a label to be linked to an input element. Without this link, you could have used a span just as well.

[Edit]

Asking for A, B, Both or None is pretty confusing when using checkboxes. You could do with just A and B, or you could use radiobuttons. Now, someone could select both 'A' and 'Both'.


you could do:

   $("button").click(function () {
       var c = $(":checked");
       c.next('label').remove();
       c.remove()
    });

If you want to remove also the <br> you could do:

   $("button").click(function () {
       var c = $(":checked");
       c.nextUntil(':checkbox').not('button').remove();
       c.remove()
    });

fiddle http://jsfiddle.net/nUjHN/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜