JL9 JL9 - 8 months ago 41
jQuery Question

Using a json value in jQuery

So I have the following json value:

{"pages": 5}
. Pages represents the number of data I have, I want to do a loop which will create a button for the number of pages that I have (5). At the moment it's not working, I'm not too sure why.

This what I've tried:

$.each(pages, function () {
$('body').append(<input type="button"/>)

When I alert pages it gives:
{"pages": 5}
in an alert box, I'm thinking I need to do a for loop from i to 5 but I don't know how to refer to the value of pages i.e. 5.

Answer Source

jquery's each iterates through the values of an array or the properties of an object, it doesn't iterate a specific number of times given a number.
On top of that I think you need to turn the json into an object first since i'm pretty confident it's still considered a string at this point: alert doesn't show objects that way in dialogs (unlike console.log).
After you parse the object you can use a for loop with the pages property

var pagesObj = JSON.parse(pages);
for( var i = 0; i < pagesObj.pages; i++) {
    $('body').append('<input type="button"/>');