Clone checked checkbox label and append to closest div with jquery -
i'm trying create search filter displays list of values user has checked in div. want cloning checkbox's label.
so when user clicks checkbox in 1 of these fieldsets, should clone , append label "list" div below. here's html:
<div class="filters"> <h2>narrow by:</h2> <fieldset> <legend>product</legend> <p> <label for="one">filter 1 label</label> <input type="checkbox" id="one"> </p> <p> <label for="two">filter 2 label</label> <input type="checkbox" id="two"> </p> <p> <label for="three">filter 3 label</label> <input type="checkbox" id="three"> </p> </fieldset> <div class="list"> </div> <fieldset> <legend>product version</legend> <p> <label for="four">filter 4 label</label> <input type="checkbox" id="four"> </p> <p> <label for="five">filter 5 label</label> <input type="checkbox" id="five"> </p> <p> <label for="six">filter 6 label</label> <input type="checkbox" id="six"> </p> </fieldset> <div class="list"> </div> </div> and here's js:
$(document).on('click', 'fieldset input:checkbox',function(){ if($(this).is(':checked')) { $(this).closest('label').clone().appendto( $(this).closest('.list')); } }); but it's not working. here's fiddle:
https://jsfiddle.net/tactics/0flnvyep/
any appreciated.
label sibling. closest looks parents. , 'list' not parent.
//don't bind on document delegates if can avoid $('.filters').on('click', 'fieldset input:checkbox',function(){ var $checkbox = $(this); if ($checkbox.is(':checked')) { $checkbox.parent().find('label').clone().appendto($('.list')); } }); that works in fiddle, after include jquery, appends list elements. $checkbox.closest('fieldset').next() instead of $('.list') should consider changing markup don't have rely on next(). logic based on positions inherently fragile.
Comments
Post a Comment