3

I have this code:

$.each(data, function(i,v){
  $('#user-grid').append(
    '<a href="my_urls">' +
      '<div>' + v.points + '</div>' +
      '<div>' + v.other + '</div>' +
    '</a>'
  );
});

Into the user grid div, I append the string with the values taken from data.

v.points and v.other are the numbers.

To this moment, everything works just fine. But what I need is to embed the for loop into the divs. In the places where I have v.points and v.other I want to put two simular FOR loops.

for(var i = 0; i < v.points; i++) {
  //here is the html line that should be passed to the div, where v.points are now
  <div>This is the point</div>
}

And almost the same for the v.other. Only with another line that should be pasted.

So basically how can I do that? I was trying to paste this loops right inside the "append()" but that didn't work out. I was also trying to create a variable inside of the loop and pass it in to the append, but got only one result, instead of all that I have needed.

8
  • 1
    Loop inside append won't work (unless it's a functional loop like map). Constructing a variable in a loop then passing it to append should be correct; please show the code you tried to run. Also, very importantly, please make a mock-up of the output you are trying to get (for instance, I don't know if you want points and other to go sequentially or interleaved). Commented Jul 27, 2015 at 3:39
  • 1
    your for loop example is not syntactically valid Commented Jul 27, 2015 at 3:41
  • please let me know your data structure! Commented Jul 27, 2015 at 3:42
  • More information would be helpful!! Commented Jul 27, 2015 at 3:42
  • is v.points an array? Commented Jul 27, 2015 at 3:42

1 Answer 1

6

I'm not sure if this is what are you looking for, this code prints 5 "This is your point" and 3 "This is your other" inside the anchor.

var data = [
    {
        points: 5,
        other: 3
    }
]

function printPoints(vPoints){
    var str = "";
    for(var i=0; i<vPoints; i++) {
        str+="<div>"+"This is your point"+"</div>";
    }
    return str;
}

function printOther(vOther){
    var str = "";
    for(var i=0; i<vOther; i++) {
        str+="<div>"+"This is your other"+"</div>";
    }
    return str;
}

$.each(data, function(i,v){
  $('#user-grid').append(
    '<a href="my_urls">' +
      printPoints(v.points)+
      printOther(v.other)+
    '</a>'
  );
});

See it on action here

Sign up to request clarification or add additional context in comments.

1 Comment

Wow, thats great! Thanks a lot.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.