Home > Enterprise >  How to Display User Input of a HTML Form
How to Display User Input of a HTML Form

Time:10-04

I've written the code below (part of my code) and I can't figure out why it won't show the user input in the form of table on the web page.

<form>
  <label for="img_tag"> What is the above picture? </label><br>
  <input type="text" name="What is the above picture?" id="input">
  <input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>
</div>
</div>
<div id="result_table">
  <table>
    <tr>
      <th> Image </th>
      <th> Tag </th>
    </tr>
    <tr id="results">
    </tr>
  </table>
</div>
<script type="text/javascript">
  var input = document.getElementByID("input").value;
  var result_row = document.getElementByID("results");
  var new_row = document.createElement("td");

  function insert_result() {
    result_row.appendChild(new_row);
    new_row.append(input);
  }
</script>

CodePudding user response:

  1. Spelling getElementById
  2. Move getting the input value inside the function that needs it
  3. you need a new cell each time, otherwise you just move the cell

you might want a new row too for each input

const inputField = document.getElementById("input");
const result_row = document.getElementById("results");

function insert_result() {
  let input = inputField.value;
  let new_row = document.createElement("td");
  new_row.append(input);
  result_row.appendChild(new_row);
}
<form>
  <label for="img_tag"> What is the above picture? </label><br>
  <input type="text" name="What is the above picture?" id="input">
  <input type="button" id="submit-button" value="Submit" onclick="insert_result()">
</form>

<div id="result_table">
  <table>
    <tr>
      <th> Image </th>
      <th> Tag </th>
    </tr>
    <tr id="results">
    </tr>
  </table>
</div>

  • Related