2

Trying to write some html to a div in 001, 002, 003 style format but I can't get it to work.

Here's the code:

function loadpics(x, url) {
  var txt, i;
  txt = "";
  for(i = 1; i < x; i++) {
    txt = txt + String.format("%03d", i) + "<br/>";
  }
  document.getElementById("myDiv").innerHTML = txt;
}

When I hopefully get it to work, I intend to load some images to the div like so:

function loadpics(x, url) {
  var txt, i;
  txt = "";
  for(i = 1; i < x; i++) {
    txt = txt + "<img src=\"" + url + "/t/" + String.format("%03d", i) + ".jpg\"></img><br/>";
  }
  document.getElementById("myDiv").innerHTML = txt;
}

Can't get the string formatting to work though. Not exactly sure what I'm doing wrong.

If anyone can put me straight it would be most appreciated.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
Lee
  • 137
  • 11

2 Answers2

1

Try using pad() instead of String.format().

function pad(number, length) {
  var str = '' + number;
  while (str.length < length) {
    str = '0' + str;
  }
  return str;
}
jnovack
  • 7,629
  • 2
  • 26
  • 40
0

Add this to your page

function pad(number, length) {
  var str = '' + number;
  while (str.length < length) {
    str = '0' + str;
  }
  return str;
}

And replace txt=txt... with this

txt +=  "<img src='" + url + "/t/" + pad(i,3) + ".jpg'></img><br/>";

Also have a look at this topic

Community
  • 1
  • 1
Dogoku
  • 4,585
  • 3
  • 24
  • 34