Page 1 of 1

Can you use PHP 'while' $count in Javascript?

Posted: Tue Feb 12, 2013 1:13 pm
by simonmlewis
I have a page that uses Javascript to toggle Divs to reveal and hide.

This is what I am trying to write:

Code: Select all

<?php
$count = 0;
while ($count < 10)  {
$count = $count + 1;
echo "<script language=\"javascript\"> 
function toggle$count() {
	var ele = document.getElementById(\"toggleText$count\");
	var text = document.getElementById(\"displayText$count\");
	if(ele.style.display == \"block\") {
    		ele.style.display = \"none\";
		text.innerHTML = \"(view info) \";
  	}
	else {
		ele.style.display = \"block\";
		text.innerHTML = \"(close info) \";
	}
} 
</script>";
}
?>
As you can see, I'm trying to create it so the numbers appear in the Javascript.
I know JS is browser based, and PHP is client based, but can you use it in this way? If you can, how am I going wrong with this?

Re: Can you use PHP 'while' $count in Javascript?

Posted: Tue Feb 12, 2013 1:43 pm
by jraede
Why don't you just use a while or for loop in JavaScript? No need for PHP here...

Re: Can you use PHP 'while' $count in Javascript?

Posted: Tue Feb 12, 2013 1:46 pm
by simonmlewis
Sorry... how? I'm not a Javascript coder at all. But I need to have toggle1, toggle2 etc. Up to a set amount.

Re: Can you use PHP 'while' $count in Javascript?

Posted: Tue Feb 12, 2013 5:36 pm
by pickle
Correct me if I'm wrong, but it looks like you're using PHP to output a set number of elements, then you have a separate function for each of those elements that toggles it's display. What you're not showing is the code that is calling your toggle1(), toggle2(), etc functions. I can only guess you have each of the toggleX() functions being called when something is clicked.

If I'm right, then you could write 1 function that accepts 1 parameter, the "count". You can rewrite your function (specifically the document.getElementById() calls) to use the passed parameter in the id string. PHP would only be needed when outputing the elements, to give them the correct "count" ID, and when outputing the calling javascript, to include the correct "count" value.