May 14, 2012

JavaScript For Loop work hows?

Question by Relax

I am using JavaScript for loop, my code is here

content = "";           
for (var i = 0; i < 13; i++) {
  var alt=glevel[i].getAttribute("name");
  if(jQuery.inArray(alt, clickArray) > -1) {
    if ($.browser.msie  && parseInt($.browser.version, 10) === 8 || $.browser.msie  && parseInt($.browser.version, 10) === 7) {
      content += "<li id='"+alt+"' style='cursor:pointer;filter:alpha(opacity=50);'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> n";
    } else {
      content += "<li id='"+alt+"' style='cursor:pointer;opacity:0.3;'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'>Click Base To Select</font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'>Click Here For Product Info</p></li> n";
    }
    //$('#'+clickArray[alt]+"").css("opacity","0.5");
  } else{
    content += "<li id='"+alt+"' style='cursor:pointer'>"+alt+"<br><div style='width:auto;'><img src='products/"+alt+".png'><br><font size='1px'></font></div><br><p style='text-decoration:none;color:#ffffff;font-size:10px;margin-top:-18px;' id='"+alt+"'></p></li> n";
  }
  $("#step_2").html(content);
}

output of this code is something like that :-

image1 image2 image3 image4 
image5 image6 
image7 image8 image9 image10 
image11 image12 image13

update:- it looks like that because of my table width and height

It works very fine, it display the real product images what i have.

now i want to display something like this :-

image1 image2 image3 image4     
image5 image6 image7     
image8 image9 image10     
image11 image12 image13

means in the first row 4 images, while 2nd,3rd, and 4th row have 3 images

Answer by Imp

for (var i = 0; i < 13; i++) {
    content += "...";

    if (i == 3)                       // after the fourth line,
       content += '<br/><br/>';       // add an empty line
    if (i > 3 && (i - 4) % 3 == 2)    // then, after every three lines
       content += '<br/><br/>';       // add an empty line
}

Answer by Starx

What about this?

for (var i = 0; i < 13; i++){
    content += "<li>...</li>";
    if(i==3 || i==6 || i==9) { content += "<br />"; }
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!