javascript - Removing items from a list that contains items selected from an auto-complete Textbox -
i've created auto-complete textbox, , div under it. when client select item textbox, automaticly appears in div, after styling css. want create event, when client clicks on styled selected items, disappear.
here js code, , jsfiddle under it, comfort.
`$(function() { /* textbox id */ $("#destinations").autocomplete({ select: function (event, ui) { /* div id */ $("#destinationschosen").html(function(i, origtext) { var selectedcountry = ui.item.value.tostring(); var currenttext = origtext.tostring(); if ((currenttext.indexof(selectedcountry) >= 0)) { alert("already exists"); return currenttext; } return currenttext + " <span class='tobutton'>" + selectedcountry + "</span>"; }) }
thanks :) idan
simplest solution existing code add line:
$('.tobutton').click(function(){$(this).remove(); });
just after $("#destinationschosen").html(...) block.
i don't recommend putting script in tag because it's not habit, since doesn't separate concerns. short answer has problems too, since getting .tobuttons each time , setting listener again.
the better way this, create tobutton dom node, , append parent div. way, can put listener on node itself.
$(function() { $("#destinations").autocomplete({ select: function (event, ui) { $("#destinationschosen").append(function(i, origtext){ var selectedcountry = ui.item.value.tostring(); var currenttext = origtext.tostring(); if ((currenttext.indexof(selectedcountry) >= 0)) { alert("already exists"); } var destination = document.createelement('span'); destination.classlist.add('tobutton'); destination.appendchild( document.createtextnode(selectedcountry)); destination.addeventlistener('click', function(){ this.remove(); }); return destination; }) } }); })
Comments
Post a Comment