Home > Software design >  Making live forms on html js
Making live forms on html js

Time:12-04

I'm making site to make table game calculations easier. So, if simplify, I have a form like this:

<input id="x"/>
<input id="y"/>

And I want to collect data of this form in live time and process them like this immediately:

<span id="x-plus-y"/> in html and document.getElementById('x-plus-y').innerHTML = x*y in js

It's very simplified but I think you got the thought.

My question is how to process x y immediately as the user enters the values into the input fields.

CodePudding user response:

This is the simple approach you can go through. I have attached a keyup event listener on every input and then invoking the updateResult function which calculates the product and displays it within the result div.

HTML

 Number 1 : <input type="number">
 <br><br>
 Number 2 : <input type="number">
 <br><br>
 <div id="result">
 </div>

JS

const inputs = Array.from(document.querySelectorAll("input"));
const resultDiv = document.querySelector("div");
const numbers = [];
for(const input of inputs) {
  input.addEventListener('keyup', updateResult);
}

function updateResult() {
   let product = 1;
   for(const input of inputs) {
       product*= parseInt(input.value,10);
    }
    if(!isNaN(product)) {
        resultDiv.innerHTML = "Product: "   product;
    }
}
  • Related