Link to home
Start Free TrialLog in
Avatar of kbios
kbios

asked on

How do I add an IF within a javascript do-while loop?

I have a do-while loop that loops for the maximum value of a localStorage variable. Each iteration creates a specific <li> statement. That logic works fine. I want to include an IF statement that will only allow the <li> statement to be created IF a specific condition of the localStorage variable is met.

If localStorage.[item + i] = "X" then I do NOT want to create the <li> statement. I simply want to increment the variable i and continue the do-while loop.

Here is the code that I am working with:

<ul>
   <script type="text/javascript">
   var i=1;
   do
   if localStorage["item" + i] = "X"
   {
    i++;
   }
   else
   {
    document.write("<li><a href='vcitemdetail.php?item="
       + localStorage["item" + i]
       + "&lsitag=" + "itag" + i
       + "&lsitem=" + "item" + i
       + "&lsdesc=" + "desc" + i
       + "'>"
       + localStorage["item" + i] + "-"
       + localStorage["desc" + i] +"</a></li>");
       i++;
   }       
 }
 while (i<=(parseInt(localStorage.trxCtr)));                        
</script>
</ul>
ASKER CERTIFIED SOLUTION
Avatar of Gurvinder Pal Singh
Gurvinder Pal Singh
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of kbios
kbios

ASKER

Thanks. The solution you provided worked. I could have used you yesterday. After many hours of testing and threads with EE I abondoned the for loop. We couldn't get it to work. We were trying to use it in the BODY not the HEAD but couldn't get it to work.

Final thought. No doubt your code is more efficient BUT is there a way to nest the IF within the do..while?
check this one


var val = parseInt(localStorage.trxCtr);
window.onload = function(){
	var html = "";
	var i = 1; 
	do
	{
		if ( localStorage["item" + i] != "X" )
		{
			html += "<li><a href='vcitemdetail.php?item="
		   + localStorage["item" + i]
		   + "&lsitag=" + "itag" + i
		   + "&lsitem=" + "item" + i
		   + "&lsdesc=" + "desc" + i
		   + "'>"
		   + localStorage["item" + i] + "-"
		   + localStorage["desc" + i] +"</a></li>";
		}       
		i++;
	}while(i < val);
	document.getElementById("list").innerHTML = html;
};

Open in new window