Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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:

<scriptsrc="../../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.

Post a Comment for "Appending A Div Tag Not Working Properly"