html() should be used for setting content in non-form elements such as div’s. ** this question has been answered a few times, which I was unaware of.
I am trying to set a value after retrieving comments from a $.ajax call. When I alert out the values of commentOutput and commentSpan, they are showing the correct data. However, when I try to set the value from those comments in a span, they do not show up, not do they appear in the generated source.
Here is the javascript. You can see the return from the POST in your console. You can also see the value it is grabbing for the span, as I have alerted it onclick.
To invoke this, just click the first picture of the cat, none of the others have comments at this point.
var ajaxOptions = {
type: 'POST',
dataType: 'json',
url: 'ajax/comments.php',
data: { id: photoID, action: 'GetComments' },
success: function(data) {
for(i=0; i<data.length; i++) {
var commentOutput = '<div><h4>'+data[i].comment_user+' says:</h4>';
commentOutput += '<span>'+data[i].comment_msg+'</span>';
commentOutput += '</div>';
var commentSpan = '#photo' + data[i].photo_id + ' .comments';
$(commentSpan).val(commentOutput);
$(commentSpan).delay('200').css('display','block');
}
}
};
Any help would be greatly appreciated,
Cheers,
Cody
Method
val()is used forinput,selectandtextareaelements.You should use
html()ortext()methods instead.NB: That’s the exact copy of my recent answer for almost the same question. Have you tried to find the solution using some searching?