Updating text on a dynamically generated span object

387 views Asked by At

I'm having an issue trying to update the text of a span object which is dynamically generated (as is the link the user clicks to update the span). When the link that encapsulates the span is clicked, I fire off an AJAX call, likePhoto, that updates the 'like' count in the database and returns the new like count. Here's the code for the button and span - like I said this is dynamically generated.

<a href="javascript:void(0);" id="LikeButton.7" name="LikeButton.7" class="like-button"><span class="badge" style="background: #f05f40;">1 Likes</span></a>

Here's the code that captures the click event of the link and fires off the likePhoto function.

$('body').on('click', 'a.like-button', function () {
    var id = this.id.replace('LikeButton.', '');
    likePhoto(id);
});

Here's the javascript code that makes the AJAX call and attempts to update span.

function likePhoto(id) {
    $.ajax({
        url: '/Ajax/LikePhoto',
        type: 'POST',
        dataType: 'json',
        data: { photoId: id },
        success: function (data) {
            var likeButton = '#LikeButton.' + id + ' span.badge';
            var value = data + ' Like';
            if (data > 1) value += 's';
            $(likeButton).text(value);
        },
        error: function (xhr, textStatus, errorThrown) {
            alert(xhr.status);
            alert(xhr.responseText);
            alert(errorThrown);
        }
    });
}

Everything appears to work just fine, except for the updated like value. I believe the problem is the one line

$(likeButton).text(value);

where the text of the span is supposed to be updated.

I would love a second pair of eyes to look over this.

Thanks!

1

There are 1 answers

0
Rory McCrossan On BEST ANSWER

The issue is with the . character in the selector. Your current selector is looking for an element with both an id of LikeButton and also a class of whatever the id value provides. Instead, you need to escape the . using \\ to prevent jQuery using it as a class operator. Try this:

var likeButton = '#LikeButton\\.' + id + ' span.badge';