Jump to content

Javascript within php loop?


Fenhopi

Recommended Posts

Hi, I have a loop that I run to retrieve all wall posts. Each post, I want to start with textbox hidden. I have a javascript code for that, but it only does it with the last post in the loop. Is there a good solution for this?

 

Code:

while($something = $something){
       <table>
       <tr>
             <td>
             echo $wallpost;
             </td>
      </tr>

       <script type="text/javascript">
			 window.onload = hide_box();
				 function hide_box(){
					 document.getElementById('myText').style.visibility='hidden';
				 }

				 </script>	
       <form name="myForm" id="form1" method="post"> 
           <input type="text" name="comments" id="myText" value="Enter in Text" onclick="this.value='';"/>  
                </form>
               </table>
}


Link to comment
https://forums.phpfreaks.com/topic/218792-javascript-within-php-loop/
Share on other sites

I think what you need there is to generate the content of the hide_box() function with the loop.  The window.onload and function hide_box() lines will need to be outside the loop.  The form also needs to be outside the loop, with only the input elements defined inside the loop.

 

If you're not clear on what I'm going on about, feel free to ask for clarification :)

Well there's a number of things that need changing.  The basic problem is you have the same code repeated with the same names, and a web browser can't understand that, so it just uses the last one.  So you also need to change the names.  The structure would be something like this:

 

<form name="myForm" id="form1" method="post">
<?php
while ($something = $something) {
?>
  <input name="myText$something" type="text" id="myText$something">
<?php
}
?>
</form>
<script type="text/javascript">
  window.onload = hide_box();
  function hide_box() {
<?php
while ($something = $something) {
?>
    document.getElementById('myText$something').style.visibility = 'hidden';
<?php
}
?>
}
</script>

 

The important things are:

 

1.  The loops are only on the parts that need repeating.  The parts outside the loop must not be repeated.

2.  Each input element has a different name, so that each javscript instruction to hide the element can act just on that input element.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.