R31D
R31D

Reputation: 39

How to stop the value of an .each loop being the same when appending buttons to a website?

    var number = 0;
    $.getJSON("blogData.json", function(data) {

    $.each(data, function (index, entry) {
        console.log(index);
        $("#posts").append("<h3>" + entry.title + "</h3>");
        $("#posts").append("<h4>" + entry.desc + "</h4>");
        $("#posts").append("<h4>" + entry.author + "</h4>");
        $("#posts").append("<p>" + entry.post + "</p>");
        $("#posts").append("<br>");
        $("#posts").append('<button onclick=save(number)>Read More</button>');
        $("#posts").append("<br><br>");
        number++;
    });

});

I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.

Upvotes: 3

Views: 31

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

You have used the variable as string type. All what you need is to concatenate the variable's value.

$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');

Upvotes: 2

Related Questions