javascript - Input.checked creates Dynamic element that needs to be bound to input -
i have filter , i'm dynamically creating li
elements when input checked, issue can't seem clear input when click on element. i'm looking bind input , dynamic together. thank in advance.
html:
<ul class="options flavorprofiles"> <li class="fl"><input type="checkbox" class="chk" id="ftsweet" value="sweet" /> <label for="ftsweet">sweet</label></li> <li class="fl"><input type="checkbox" class="chk" id="ftsavory" value="savory" /> <label for="ftsavory">savory</label></li> <li class="fl"><input type="checkbox" class="chk" id="ftspicy" value="spicy" /> <label for="ftspicy">spicy</label></li> <li class="fl"><input type="checkbox" class="chk" id="fttangy" value="tangy" /> <label for="fttangy">tangy</label></li> </ul> <div class="results-label">filters applied: <a href="javascript:void(0)" id="filterclear">remove all</a> </div> <ul id="results"></ul>
js:
$(document).ready(function() { var $li; // adds 'expand' .cat-filter on click $('.filter-header').click(function() { if($(this).hasclass("expand")) { $(this).removeclass("expand"); } else { $(this).addclass("expand"); } }); // turns filter groups on/off $('.filter-header.secpb').click(function() { $('.options.prodbenefits').toggle(); }); $('.filter-header.secsd').click(function() { $('ul.options.specialdiets').toggle(); }); $('.filter-header.secfp').click(function() { $('ul.options.flavorprofiles').toggle(); }); // adds/removes input value text under results $('.options input').change(function() { if (this.checked) { $li = $('<li class="active-filter"></li>'); $li.text(this.value); $('#results').append($li); var input = this; $li.click(function () { $(input).click(); }); } else { $('li:contains('+this.value+')', '#results').remove(); } }); // clears filter results on click $('#filterclear').click(function() { $('#results').empty($li); }); }); // dom ready
this line wrong:
$($li).on("click", this, clear(this.value));
it intends bind function event handler newly inserted li
element, instead call clear
right there. means not binding event handler. 1 solution use clear.bind(null, this.value)
argument.
also, second argument strange: pass dom element (this
), jquery interpret being data passed event.data
. cannot interpret selector (if intention), because have string.
thirdly, making jquery object of jquery object. write $li
instead of $($li)
.
depending on wanted there, can use syntax:
$li.click(clear.bind(null, this.value));
but want mimic un-checking corresponding checkbox (input), easier trigger click on it. use instead:
var input = this; // reference `this` lost, save $li.click(function () { $(input).click() // trigger click event on checkbox });
so clicking li
element trigger click on checkbox, , execute event handler have on it. else
part in handler executed.
Comments
Post a Comment