Javascript Form How to - Get the Input content of a form as a variable








Question

We would like to know how to get the Input content of a form as a variable.

Answer


<!DOCTYPE html>
<html>
<body>
  <form>
    <input type="text" id="unit">
  </form><!--from  ww  w . j a v  a2 s .c o  m-->
  <br>
  <button class="btn btn-sm btn-danger" id="confirm">Confirm</button>
  <br>
  <br>
  <h4>
    It is <span id="unitType">[?]</span>.
  </h4>
  <script type='text/javascript'>
    document.getElementById("confirm").onclick = function() {
        var unitInput = document.getElementById("unit").value;
        var unitType = document.getElementById("unitType");
        unitType.innerHTML = unitInput;
    };    
    </script>
</body>
</html>

The code above is rendered as follows: