-1

I am trying to create something like stackoverflow.com tag cloud. I am able to display the tags but stuck on how to capture which tag element cancel button was clicked.

The cancel buttons are created dynamically using jquery on click of btnAdd.

$("#<%=btnAdd.ClientID%>").on('click',function(){
  var tagText = $('#<%=txtTag.ClientID%>').val();
  var btnCancel = '<button class="btn btn-default">X</button>';

  var tagTextDiv ='<div class="tagElement">' + tagText + btnCancel +'</div>';

  $("#divTagCloud").append(' ' + tagTextDiv);
});

HTML is

<div class="col-xs-12 col-sm-6">
   <asp:TextBox runat="server" />
</div>
<div class="col-xs-12 col-sm-6">
   <asp:Button runat="server" id="btnAdd"/>
</div>


<div class="col-xs-12 col-sm-12">
   <div id="divTagCloud"></div>
</div>

I want to remove the tag i.e corresponding tagTextDiv on click of corresponding cancel button.

How to do this ?

Mudassir Hasan
  • 26,105
  • 18
  • 90
  • 124

1 Answers1

1

Create the tag and button elements as jquery objects instead of just strings. That allows you to attach event handlers before inserting them into the DOM.

$("#<%=btnAdd.ClientID%>").on('click',function(){
    var tagText = $('#txtTag').val();
    // Create the tag and cancel button elements
    var btnCancel = $('<button class="btn btn-default">X</button>');
    var tagTextDiv = $('<div class="tagElement">' + tagText + '</div>');
    // insert the cancel button into the tag element
    tagTextDiv.append(btnCancel);
    // attach an onclick event handler to the cancel button, that removes the tag.
    btnCancel.click(function() {
        // "this" is the element that the event handler is attached to, in this case, the cancel button
        // get its' parent (the tag text div) and remove that from the DOM
        $(this).parent().remove();
    });
    // finally, insert the new tag into the DOM
    $("divTagCloud").append(tagTextDiv);
});