Deleting items from a list containing selected items from a self-completed text box

advertisements

I've created an auto-complete Textbox, and a div under it. When the client select an item from the Textbox, it automaticly appears in the div, after styling with CSS. What I want to do now is to create an event, that when the client clicks on the styled selected items, they will disappear.

here is the JS code, and jsfiddle under it, for your 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>";
    })
}

http://jsfiddle.net/dgu1ncsj/

thanks :) Idan


Simplest solution for this existing code is to add the line:

        $('.toButton').click(function(){$(this).remove(); });

Just after the $("#DestinationsChosen").html(...) block.

I don't recommend putting script in the tag itself because it's not a good habit, since it doesn't separate concerns. But my short answer has problems too, since it is getting all .toButtons each time and setting the listener again.

The better way to do this, is to create the toButton as a DOM node, and append it to the parent div. This way, you can put the listener on the 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;
            })
        }
    });
})