AdiT
AdiT

Reputation: 549

Problems with remove checkbox dynamically.

I have looked all over and found many similar threads, but none of them really answered my question with this specific situation:

I want to, when I create a dynamic Checkbox, and want to remove the specific checkbox and the text by clicking on the trash image. It seems to not work when I want to remove.

Live Demo

HTML:

<input type="text" id="checkBoxName" />
<input type="button" value="ok" id="btnSaveCheckBox" />

Jquery:

$(document).ready(function() {
    $('#btnSaveCheckBox').click(function() {
        addCheckbox($('#checkBoxName').val());
        $('#checkBoxName').val("");
    });

});

    function addCheckbox(name) {
       var container = $('#cblist');
       var inputs = container.find('input');
       var id = inputs.length+1;

       $('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
       $('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);

       $('<img />', { "src": "/Pages/Images/trashDialog.png", "class": "removeCheckBoxDialog"}).appendTo(container);

            $('.removeCheckBoxDialog').on('click', function (e) {

                $("#cb :checkbox").remove();

            }); 


       $('<br/>').appendTo(container);
    }

CSS:

.removeCheckBoxDialog {
    margin-left:10%;
    cursor:pointer;
}

Upvotes: 2

Views: 205

Answers (4)

Zword
Zword

Reputation: 6793

Try below jQuery:

$('#cblist').on('click','.removeCheckBoxDialog', function (e) {            
    $('#'+$(this).prev().attr('for')).remove();
    $(this).next('br').remove().prev().addBack().remove();
    $(this).remove();
}); 

Fiddle


The above wasnt clearing the label so i edited it a bit :

$('#cblist').on('click','.removeCheckBoxDialog', function (e) {            
    $('#'+$(this).prev().attr('for')).remove();
    $(this).next('br').remove();
    $(this).prev().remove();
    $(this).remove();
}); 

Fiddle

Upvotes: 1

Neville Nazerane
Neville Nazerane

Reputation: 7019

Try this. I have done the following:

  1. Appended a div to contain each of the 3 components
  2. I used var container2 = $("div:last-of-type", container); to select this div.
  3. Finally I simply used $(this).parent().remove(); To get the parent and remove it.

And also I removed the <br> as the div does the job of new line by default.

Upvotes: 0

laaposto
laaposto

Reputation: 12213

Add this

$("#cb"+id).remove();
    $('label[for=cb'+id+']').hide();
    $(this).nextAll('br').remove();
    $(this).remove();

to your click function

$('.removeCheckBoxDialog').on('click', function (e) {

            $("#cb"+id).remove();
            $('label[for=cb'+id+']').remove();
            $(this).nextAll('br').remove();
            $(this).remove();

        });

DEMO

Upvotes: 1

Deepu--Java
Deepu--Java

Reputation: 3820

Try this

 $("#cb"+id).remove();
 $('label[for=cb'+id+']').remove();

Upvotes: 0

Related Questions