After selecting a checkbox, the text/value is displayed in an li element. However, if I uncheck the first box and check the second one, I want to remove the text/value associated with the first checkbox as shown below:
Here is my code snippet:
$('input[type="checkbox"]').bind('change', function() {
var alsoInterested = '';
$('input[type="checkbox"]').each(function(index, value) {
if (this.checked) {
/*add*/ /*get label text associated with checkbox*/
alsoInterested += ($('label[for="'+this.name+'"]').html() + ', ');
}
});
if (alsoInterested.length > 0) {
alsoInterested = alsoInterested.substring(0,alsoInterested.length-2);
} else {
alsoInterested = '';
}
console.log(alsoInterested);
var li = $('<li>'+alsoInterested+'</li>').appendTo('#list');
$("#ul").append(li);
});
$('li').click(function()
{
alert('test');
});
li
{
float:left;
width: auto;
background: #ccc;
margin:10px;
display:inline-block;
cursor: pointer;
}
li:hover::after {
content: 'x';
color: white;
margin: 10px;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="bannanasChk" name="bannanasChk" value="N">
<label for="bannanasChk" class="light">Bannanas</label>
<input type="checkbox" id="carChk" name="carChk" value="N">
<label for="carChk" class="light">Car Monkeys</label>
<input type="checkbox" id="apesChk" name="apesChk" value="N">
<label for="apesChk" class="light">Apes</label>
<input type="checkbox" id="repairChk" name="repairChk" value="N">
<label for="repairChk" class="light">Car Repair</label>
<br>
<ul class="list-unstyled" id="list">
</ul>