I am trying to create a tags feature where items are appeneded / removed to a list when it's associated input is toggled. The code is able to append the item to the list however when unchecked, the item isn't removed.
I need it so that when I check the input, the span
is added to the list via the append, and when the input is unchecked, the corresponding item in the list is removed. Also if the appended button
is pressed, the item is removed and its aossicated checkbox is unchecked.
$(document).ready(function() { $(document).on("change", "input", function() { if (this.checked) { $('input[value="' + this.value + '"]:checkbox') .prop("checked", this.checked) .addClass("checked"); var html = "<span class='item' data-feed=' " + $(this).val() + "'>" + $(this).val() + " <button>X</button>" + "</span>"; $(".feed__list").append(html); } else { $('input[value="' + this.value + '"]:checkbox') .prop("checked", false) .removeClass("checked"); $('[data-feed="' + this.value + '"]').remove(); } }); });
body { display: flex; } .feed__list { flex: 1; border: 2px solid; pading: 3rem } .feed__tags { display: flex; padding: 1.3rem; border: 1px solid } .feed__tag label { display: flex; align-items: center; user-select: none; cursor: pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="feed"> <div class="feed__tags"> <div class="feed__tag"> <input id="i0" type="checkbox" name="checkbox" value="dog"> <label for="i0"> <div>Dog</div> </label> </div> <div class="feed__tag"> <input id="i1" type="checkbox" name="checkbox" value="cat"> <label for="i1"> <div>Cat</div> </label> </div> </div> <div class="feed__tags"> <div class="feed__tag"> <input id="x0" type="checkbox" name="checkbox" value="dog"> <label for="x0"> <div>Dog</div> </label> </div> <div class="feed__tag"> <input id="x1" type="checkbox" name="checkbox" value="cat"> <label for="x1"> <div>Cat</div> </label> </div> </div> </div> <div class="feed__list"> </div> </div>
没有评论:
发表评论