I am building a page where the users can add tags (or keywords) similar to SO. When a new tag is added, I generate a div and append that to the container div through the jquery below which works fine.
// add new keyword
$('.Add_Keyword').click(function () {
// Perform the ajax post
$.post("/Content/_AddKeyword", { "keyword": document.getElementById('Keyword').value, "ContentId": document.getElementById('ContentId').value },
function (data) {
// Successful requests get here
// Update the page elements
document.getElementById('Keyword').value = '';
var new_div = $('<div class="float-left" id=tag-"' + data.KeywordId + '">' + data.Keyword + '<a href ="#" class="Remove_Keyword" data-id="' + data.KeywordId + '">[X]</a></div>');
$('#all_tags').append(new_div);
});
});
The newly generated divs have id=tag- and contain the keyword (text) and anchor tag, which can be clicked to remove this keyword. Following is the jquery to remove the tag:
// remove keyword
$('.Remove_Keyword').click(function () {
var keywordToRemove = $(this).attr("data-id");
$.post("/Content/_RemoveKeyword", { keywordId: keywordToRemove },
function (data) {
// Successful requests get here
// Update the page elements
debugger
if (data.IsDeleted) {
var del_div = $('#tag-' + data.DeleteId);
del_div.hide();
}
});
});
This works for divs created with GET, but does not work for dynamically generated divs..... any ideas why??? Following is the html:
<fieldset>
<legend>Keywords</legend>
<ol>
<li>
@Html.LabelFor(m => m.Keyword)
@Html.TextBoxFor(m => m.Keyword)
</li>
<li>
<a href="#" class="Add_Keyword">Add</a>
</li>
</ol>
</fieldset>
<div id="all_tags">
@foreach (var item in @Model.KeywordList)
{
<div class="float-left" id="[email protected]">
@item.Keyword
<a href="#" class="Remove_Keyword" data-id="@item.KeywordId">[X]</a>
</div>
}
</div>