I have a form with three input boxes, what I want to do, as I will enter numbers in those input boxes, I want to see live math calculation in the div area
function ABC() {
const first = document.querySelector('.first')
const second = document.querySelector('.second')
const third = document.querySelector('.third')
const total = document.querySelector('.math')
const ab = first * second
const cd = ab % third
const ef = ab - cd
total.innerHTML = ef
}
<form>
<input class="first" type="text" value="" />
<input class="second" type="text" value="" />
<input class="third" type="text" value="" />
</form>
<div class="math" onKeyUp="ABC()">
<div>
CodePudding user response:
You need to fix at least two issues:
- To get the values from inputs, you need to access their
value
property - There is no
keyup
event that will fire on adiv
, put it at the container element of theinput
elements, i.e. on theform
element.
function ABC() {
const first = document.querySelector('.first').value;
const second = document.querySelector('.second').value;
const third = document.querySelector('.third').value;
const total = document.querySelector('.math')
const ab = first * second
const cd = ab % third
const ef = ab - cd
total.innerHTML = ef
}
<form onkeyup="ABC()">
<input class="first" type="text" value="" />
<input class="second" type="text" value="" />
<input class="third" type="text" value="" />
</form>
<div class="math">
<div>
Better still:
- Attach an event listener in code, not with a HTML attribute.
- Listen to the
input
event, which also fires when you make changes via the context menu, via text drag/drop or other non-keyboard methods. - Don't use
innerHTML
when all you want to do is output plain text. - End your statements with semi-colon. It is a bad habit to leave that to the automatic semicolon insertion algorithm.
- Give your input elements some initial value, and call the ABC function upon page load so that the calculation will already work from the start.
- Use
type="number"
for your input elements.
const form = document.querySelector("form");
form.addEventListener("input", ABC);
function ABC() {
const first = document.querySelector('.first').value;
const second = document.querySelector('.second').value;
const third = document.querySelector('.third').value;
const total = document.querySelector('.math');
const ab = first * second;
const cd = ab % third;
const ef = ab - cd;
total.textContent = ef;
}
ABC();
<form>
<input class="first" type="number" value="1">
<input class="second" type="number" value="1">
<input class="third" type="number" value="1">
</form>
<div class="math">
<div>