0

Just want to display the reviews using jquery but it displays only the last review. Could you help me please.

$.each(data.results, function(i, res) {

        var item = $('<div>'),                    
            head = $('<h4>'),
            info = $('<p>');

        head.html(res.title);
        info.html(res.review_text+'<hr>'); 

        item.append(head,info);

        $("#review_list").html(item);
    }); 

Update:

Actually I tried in this way and it worked without using append.

 var item = $('<div>'); // moved item outside loop

$.each(data.results, function(i, res) {


            var head = $('<h4>'),
                info = $('<p>');

            head.html(res.title);
            info.html(res.review_text+'<hr>'); 

            item.append(head,info);

        });

 $("#review_list").html(item); // used html outside loop 
EducateYourself
  • 971
  • 2
  • 13
  • 32

1 Answers1

1

This is because every time you replace everything with new content. You can do this:

$.each(data.results, function(i, res) {

    var item = $('<div>'),                    
        head = $('<h4>'),
        info = $('<p>');

    head.html(res.title);
    info.html(res.review_text+'<hr>'); 

    item.append(head,info);

    $("#review_list_is_got").append(item);
}); 

Basically you have html which will replace the content of the specified item, and append which will add to the container you have, and seems what you want.

Mimo
  • 6,015
  • 6
  • 36
  • 46
  • thanks for the answer. I have a problem when I use "append". It works ok when I press "Load Reviews" link for the first time. But when I press the link twice, it displays duplicate reviews. – EducateYourself Aug 30 '14 at 08:08
  • In that situation you have to handle the call to the function differently, for example disabling the button while the call is performed – Mimo Aug 30 '14 at 08:09
  • actually, I use a link, not a button. Is there a way to disable link? – EducateYourself Aug 30 '14 at 08:10
  • yes, there are many ways, have a look at this question: http://stackoverflow.com/questions/2091168/disable-a-link-using-css – Mimo Aug 30 '14 at 08:11
  • I have just updated my question. Could you please have a look on it to check if it is correct. – EducateYourself Aug 30 '14 at 08:20
  • Yes it is correct. You are basically doing the same thing, but a little bit less efficient since you are repopulating the `#review_list_is_got` item completely at every cycle. – Mimo Aug 30 '14 at 08:35