0

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>

3 Answers 3

2

Use .on() to attach events for dynamically generated html elements:

$("div[id^=tag-]").on('click','.Remove_Keyword',function (e) {
        e.preventDefault();
        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();
                }
            });
});
Sign up to request clarification or add additional context in comments.

5 Comments

I have changed the code accrodingly..... but I am still not able to delete the dynamically added divs. Although the function triggers, the "del_div" div does not seem to exist in the rendered html.... Am i doing something wrong in the Add function??
It looks everything fine.. can you check in POST method whether you are getting data? and check console for errors.
When I view the source.... I can not find the dynamically created divs in the DOM.... is that right behaviour? The POST method is returning data. There are no console errors
the delegate idea worked..... also there was a typo in my div generation code..... :) All good now
@Purusartha: Good Bro. :)
1
$(body).on('click', 'newelementid',function () {
$('.Remove_Keyword')
});

Delagation

On in Jquery

Comments

1

You have a misplaced quote in your code on the id, for one:

var new_div = $('<div class="float-left" id=tag-"'

should be

var new_div = $('<div class="float-left" id="tag-'

And you probably don't want to apply your .RemoveKeyword click event before you have even built the dynamic divs in the code... so I would apply that event after the last line of your ajax call ($('#all_tags').append(new_div);) once the element is actually there.

Example JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.