0

I am running a foreach loop and I want to be able to change the content and class of the affected div elements.

foreach ($fields as $key => $value) { ?>
    <script type="text/javascript">
        document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
    </script> 
<?php } ?>
5
  • 4
    That makes no sense, there's no reason to output javascript that changes the innerHTML when you can do it directly in PHP ? Commented May 14, 2015 at 9:41
  • @sgtBOSE The problem is that it doesnt change the content . Commented May 14, 2015 at 9:54
  • @adeneo how can i change a div content with php ?? Commented May 14, 2015 at 9:54
  • Start by showing us how you create the HTML in the loop ? Commented May 14, 2015 at 9:56
  • Are you sure that your $key is correct? Commented May 16, 2015 at 16:16

3 Answers 3

1
foreach ($fields as $key => $value) { ?>
   <script type="text/javascript">
    document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
 </script> 

you better use it like this .

<script>
    <?php foreach ($fields as $key=>$value){ ?>
          document.getElementById("<?php echo $key; ?>").innerHTML = "<?php echo $value; ?>";
    <?php } ?>
</script>

and make sure you have all correspoinding elements with the same id as $key in this script for example.

    <?php foreach($fields as $key=>$value){ ?>

         <div id="<?php echo $key; ?>" ></div>

    <?php } ?>

Regards

Sign up to request clarification or add additional context in comments.

Comments

0

You may use only one part...

  • server-side with PHP and more tempting

  • client-side with Javascript

For the last approach, it could be okay to store / request the array as an JavaScript array, or json object and iterate it / update the existing elements during a loop after the site has been loaded.

A mixture of both may lead to a non-maintainable source and more render and execution time as expected.

Comments

0

I have not got what you actually want, But lets with this code. It may help you...

<script type="text/javascript">
    $( document ).ready(function() {
      <?php
          foreach ($fields as $key => $value) {  
       ?>
        document.getElementById('<?php echo $key ?>').innerHTML = '<?php echo $value ?>';
      <?php
          }  
      ?>
    });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.