javascript get form value code example

Example 1: javascript get form data

<html>
    <form id="myForm">
        <input type="text" name="email" value="[email protected]">
    </form>
    <p id='text'></p>

    <script>
        window.setInterval(()=>{
            var myForm = document.getElementById('myForm');
            var text = document.getElementById('text');

            text.innerText = myForm.elements['email'].value;
        }, 1);
    </script>
</html>

Example 2: js get value from form input

// having form like this

<form>
  <div>
  	<label for="number">Give me number</label>
	<input type="number" id="number">
  </div>
  <div>
    <button class="btn">Click</button>
  </div>
</form>

// this is how u get a value (number)
document.querySelector("form").addEventListener("submit", get_number);
function get_number(e){
    const n = document.getElementById("number").value;
    console.log('n:', n)
    e.preventDefault();
}

Tags:

Html Example