1

how to remove elements from a div when checkbox is unchecked ?

function dispCmpName(id) {

            var campdip = $('#camp' + id).html();
            if ($("#campaign-name-disp").text().search("" + campdip) === -1) {
                $("#campaign-name-disp").append('<br/><div id=campSub'+ id +'>'+ campdip + '<img src="./images/remove.png"alt="Delete Campaign" title="Delete Campaign" style="cursor: pointer" onclick="deleteCamp()"/>'+'</div>');
            } else {
               alert(id);
               $('#campaign-name-disp).remove(campdip);
            }
        }
<div>
  <p id="campaign-name-disp"></p>
</div>

<input type="checkbox" class="checkBoxClass1" id="${campDetails.campaignId}" name="campaignId" value="${campDetails.campaignId}" onclick="dispCmpName(${campDetails.campaignId})"/>

<td id="camp${campDetails.campaignId}">${campDetails.campaignName}</td>

whenever i check a check box the dispCmpName function gets called and adds the campaign name under a div to the p tag with id campaign-name-disp. And when i uncheck the checkbox i want to remove that campaign name from my p tag using the div ids. Could anyone help me out in how to remove the name when unchecked.

Note: each div id is unique. my div ids look like this

    <p id="campaign-name-disp">
<div id="campSub382581148">campaign name 1</div>
<div id="campSub382581148">campaign name 2</div>
</p>
Nidhi
  • 21
  • 6

2 Answers2

2

You can do it more neatly using a change event, and use the "checked" property of the checkbox to decide what to do. And you need to wrap each campaign name (I'm assuming there can be multiple ones) in an element so you've got something to use as a handle when removing them:

$(".campaignCheckBox").change(function(event) {
  var id = $(this).val();

  if ($(this).prop("checked") == true) {
    $("#campaign-name-disp").append('<span id="campaign-name-' + id + '">' + $('#camp' + id).html() + '</span>');
  }
  else {
    $("#campaign-name-" + id).remove();
  }
});

And

<input type="checkbox" class="checkBoxClass1 campaignCheckBox" id="${campDetails.campaignId}" name="campaignId" value="${campDetails.campaignId}" />
ADyson
  • 57,178
  • 14
  • 51
  • 63
1

When a function get called you can check if checkbox is 'checked' or not. Here you can see example how to check it:

if(document.getElementById(<id>).checked) {}

How to check whether a checkbox is checked in jQuery?

Community
  • 1
  • 1
kropla
  • 163
  • 10