I have tried to create a function for each input submit. The first input is for sum, the second for subtraction, third division and fourth multiplication. When I click on input (id="soma"), the console shows that soma() is not a function, but I alreasy created a function soma(); See the code below:
const formHtml = document.querySelector('#form');
const campo1 = document.querySelector('#campo1');
const campo2 = document.querySelector('#campo2')
const resultado = document.querySelector('.resultado');
const num1 = Number(campo1.value);
const num2 = Number(campo2.value);
formHtml.addEventListener('submit', function(e) {
e.preventDefault();
const soma = document.querySelector('#soma');
soma.onclick() = function somar() {
const somando = num1 + num2;
resultado.innerHTML += `A soma foi ${somando}`;
}
const sub = document.querySelector('#sub');
sub.onclick() = function sub() {
const subtraindo = num1 - num2;
resultado.innerHTML += `A subtração foi ${subtraindo}`;
}
const divi = document.querySelector('#divi');
divi.onclick() = function divi() {
const dividindo = num1 / num2;
resultado.innerHTML += `A divisão foi ${dividindo}`;
}
const multip = document.querySelector('#multip');
multip.onclick() = function multip() {
const multiplicando = num1 * num2;
resultado.innerHTML += `A multiplicação foi ${multiplicando}`;
}
});
<form action="" id="form">
<input type="number" name="campo1" id="campo1">
<input type="number" name="campo2" id="campo2">
<input type="submit" value="soma" id="soma" onclick="somar()">
<input type="submit" value="subtração" id="sub" onclick="sub()">
<input type="submit" value="divisão" id="divi" onclick="divi()">
<input type="submit" value="multiplicação" id="multip" onclick="multip()">
<div class="resultado">
</div>
</form>
3
Answers
The event listeners are attached to each button individually using addEventListener.
Inside each event listener, the values of campo1 and campo2 are retrieved, and the corresponding calculation is performed.
The result is directly updated in the
.resultado
div by assigning the desired text to the innerHTML property.You don’t need to create a function for each button, you can just get all
type=button
with querySelectorAll, then loop thru each element and use addEventListener to each element.Once an button is clicked you can do
console.log(op.id)
and it will print the id of the button that was clicked and thats how you will know which operation to do wich aswitch/case
A very clever approach for this in order to keep the code as clean as possible is to assign an id to each button which matches the name of the function you want to use for that button.
Than we can easily use the appropriate function for each button click.