user1668543
user1668543

Reputation: 309

Appending a Div tag not working properly

I am developing MVC 3 application and using razor syntax.

In this application I am giving commenting facility.

I have given the facility to adding a comment and it saved in DB.

and when user clicks on delete button it displays the message as "Clicked".

When user load entity, previously added comments get displayed on page with delete button and when user click on that button the "clicked" msg appears.

enter image description here

now, when user add a new comment, it saved in DB sucsessfully and also appear on the page along with Delete button.

now when user click on delete button msg wontcome... ( I append the Div tag while loading the new comment from DB)

I think , there is a issue regarding append, means previous comments Delete button work well, but when I add button using append it wont works...

Here is the code, saves comment in DB and in sucsess , it creates HTML Code with button to disply the data on the page.

<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#AddCommentButton').click(function () 

        {
     if (document.getElementById('Comment').value != "")

         $.ajax({

                type: 'post',
                url: '/Comment/SaveComments',
                dataType: 'json',
                data:
                { 

                 'comments' : $('#Comment').val(), 
                 'EType' : @Html.Raw(Json.Encode(ViewBag.EType)), 
                  'EId' : @Html.Raw(Json.Encode(ViewBag.EId))

                },
                success: function (data) {

                      $("p.p12").append('<button type="button" id = "1" class="deleteComment">Delete</button><br />')

                   alert(data.Id);

                }

            });
        });
    });
</script>

and user clicks on Delete Button I have written this code.

$(document).ready(function () {
        $(".deleteComment").click(function ()
         {
            alert("Clicked");


        });
    });

For previous comments, when user click on the delete button "Clicked' msg comes but when user clicks on newly added comment's delete button, msg wont come ...

Upvotes: 0

Views: 372

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

You need to subscribe to the click event of this delete button in a lively manner since it was added dynamically to the DOM. You cannot just use .click() in your document.ready because the delete button doesn't yet exist at this stage. So depending on the jQuery version that you are using there are 3 ways:

.on(), .delegate() or .live().

The recommended approach is .on() which is supported starting from jQuery 1.7:

$(document).on('click', '.deleteComment', function() {
    alert("Clicked");
}); 

And you no longer need to wrap this in a document.ready.

If you are using an older version here's the same with .delegate() (introduced in jQuery 1.4.2):

$(document).delegate('.deleteComment', 'click', function() { 
    alert('Clicked'); 
});

And if you are using an even older version of jQuery, well, you should upgrade and if you don't want to upgrade use .live():

$('.deleteComment').live('click', function() { 
    alert('Clicked'); 
});

And while I am at your code here are a couple of other remarks.

Replace:

<script src="../../Scripts/jquery.js" type="text/javascript"></script>

with:

<script src="@Url.Content("~/Scripts/jquery.js")" type="text/javascript"></script>

and also replace:

url: '/Comment/SaveComments',

with:

url: '@Url.Action("SaveComments", "Comment")',

And by the way as an alternative to putting the url in your javascript you could directly use the value of your AddCommentButton. You haven't shown it your markup I assume that it might look like this:

@Html.ActionLink("Add a comment", "SaveComments", "Comment", null, new { id = "AddCommentButton" })

And now all that's left is to unobtrusively AJAXify it:

$(document).ready(function () {
    $('#AddCommentButton').click(function (evt) {
        evt.preventDefault();

        var comment = $('#Comment').val();
        if (comment == '') {
            alert('Please enter a comment');
            return;
        }

        $.ajax({
            type: 'post',
            url: this.href,
            data: { 
                comments : comments, 
                EType: @Html.Raw(Json.Encode(ViewBag.EType)), 
                EId: @Html.Raw(Json.Encode(ViewBag.EId))
            },
            success: function (data) {
                // You probably need to embed the comment id as a HTML data-* attribute
                // to the button instead of using a hardcoded id="1" value
                // which by the way is an invalid value of an id in HTML:
                $('p.p12').append(
                    $('<button/>', {
                        'class': 'deleteComment',
                        'html': 'Delete',
                        'data-id': data.Id
                    }).after($('<br/>'))
                );
            }
        });
    });
});

and now inside your Delete button click callback you will be able to access the id of the comment to be deleted:

$(document).on('click', '.deleteComment', function() {
    var commentId = $(this).data('id');
    // TODO: delete the comment
}); 

Absolutely never hardcode urls in an ASP.NET MVC application. Always use url helpers to generate them. The reason for this is that url helpers take into account the routing setup and the virtual directory in which your application might be running. So if later you decide to change the pattern of your routes or even deploy your application in IIS you will no longer need to go through all your pages and replace those wrongly hardcoded urls for your application to work.

Upvotes: 3

Related Questions