html - How do I remove element using .click and .remove in jQuery -
here jsfiddle
and here code.
html
<h2>todo list</h2> <div id='additem'> <input type='text' name='additem'/> <button>add item</button> </div> <div id='todolist'> <ol> </ol> <!-- add item "additem" input field --> </div>
js
$(document).ready(function(){ $('button').click(function(){ var item = $('input[name=additem]').val(); $('ol').append('<li>'+ item +' <button id="remove">remove</button></li>'); }); $("#remove").click(function(){ $(this).parent('li').remove(); }); });
you need use on() dynamically added elements using event delegation. can delegate event parent element available when bind event using on or can use document
otherwise.
$(document).on("click", "#remove", function(){ $(this).parent('li').remove(); });
delegated events
delegated events have advantage can process events descendant elements added document @ later time. picking element guaranteed present @ time delegated event handler attached, can use delegated events avoid need attach , remove event handlers. element container element of view in model-view-controller design, reference
Comments
Post a Comment