Delete li element if not checked

I can dynamically add a new li element to the checked flag event. However, I cannot delete the same in the unchecked event.

 $(document).ready(function() { var value; $(".tmCheckbox").change(function() { if (this.checked) { value = $(this).val(); $('.ul_sec').append($('<li>', { text: value })); } else { // $(this).parent().remove(); } }); }); 

HTML CODE:

 <h3>MY SELECTION </h3> <ul class="ul_sec" style="display: block;"> <li><input type="checkbox" name="filter" value="">Random Text 1</li> <li><input type="checkbox" name="filter" value="">Random Text 2</li> </ul> <h3>FILTER</h3> <ul style="display: block;"> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 1">Random Text 1</li> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 2">Random Text 2</li> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 3">Random Text 3</li> </ul> 
+6
source share
3 answers

Filter the li element based on textual content with the filter() method and remove it with remove() .

 var $this = this; $('.ul_sec li').filter(function(){ return $(this).text() == $this.value; }).remove(); 

 $(document).ready(function() { var value; $(".tmCheckbox").change(function() { var value = $(this).val(); if (this.checked) { $('.ul_sec').append($('<li>', { html: this.outerHTML + value })); } else { $('.ul_sec li').filter(function() { return $(this).text() == value; }).remove(); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h3>MY SELECTION </h3> <ul class="ul_sec" style="display: block;"> </ul> <h3>FILTER</h3> <ul style="display: block;"> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 1">Random Text 1</li> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 2">Random Text 2</li> <li><input class="tmCheckbox" type="checkbox" name="filter" value="Random Text 3">Random Text 3</li> </ul> 
+2
source

Just use remove() for the purpose where it is added

Like this:

 $(document).ready(function() { var value; $(".tmCheckbox").change(function() { if (this.checked) { value = $(this).val(); $('.ul_sec').append($('<li>', { text: value })); } else { $('.ul_sec li').last().remove(); } }); }); 
0
source

document.getElementById("yourid").remove(); by specifying the identifier <li> that you just added.

-one
source

Source: https://habr.com/ru/post/1015649/


All Articles