Search code examples
javascriptphphtmlformsinnerhtml

innerHTML examples work well until I incorporate them into other Javascript


I experiment successfully with W3Schools examples of using innerHTML, such as https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_form_elements My goal is to read and write form control displayed values to/from JavaScript code when I invoke "onclick"s.

But when I simply place an example in an appropriate spot in an existing PHP script, nothing appears on the webpage when I click the "Try It" button. Granted, the existing code has its own form, other Javascript functions and references to $_POST values.

Here is an excerpt of my PHP script, including the example "Donald Duck" code. Note, neither myFunction() nor myFunction2() produced any screen change when invoked. Nor did a version that used document.write(x)

</style>

<script type="text/javascript">
...

function myFunction() {
    var x = document.getElementById("rmOne");
    var txt = "";
    var i;
    for (i = 0; i < x.length; i++) {
        txt = txt + x.elements[i].value + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

function myFunction2() {
  $_POST.forEach(output)
}

function output(element, index, array) {
  document.write(index + element + "<br>")
}
</script>

</head>
<body>


<form id="myForm" action="/action_page.php">
  First name: <input type="text" name="fname" id="fname" value="Donald"><br>
  Last name: <input type="text" name="lname" value="Duck"><br>
  <input type="submit" value="Submit">
</form>

<p>Click the "Try it" button to display the value of the first element in the form.</p>

<button onclick="myFunction2()">Try it</button>

<p id="demo"></p>

<?php

require_once "config.azsb.php";
require_once "functionsarrays.azsb.php";

if ( isset( $_POST["roomSel"] ) )
  $room = $_POST["roomSel"];

Appreciations in advance!


Solution

  • <script type="text/javascript">
    ...
    
    function myFunction() {
        var x = document.getElementById("rmOne");
        var txt = "";
        var i;
        for (i = 0; i < x.length; i++) {
            txt = txt + x.elements[i].value + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
    
    function myFunction2() {
      <?php
      foreach($_POST as $index => $element):
      ?>
      output(<?= $index ?>, '<?= $element ?>');
      <?php endforeach; ?>
    }
    
    function output(element, index, array) {
      document.write(index + element + "<br>")
    }
    </script>