Home > other >  Adding two numbers in javascript from two inputs in a form
Adding two numbers in javascript from two inputs in a form

Time:10-18

I am new in JavaScript. As a result I was practicing some codes that reads two numbers from a form and display the result on a button click. I also want to add a reset button to start a new calculation. The problem is the result field is not updating on button click but the reset button is working. Below is my code:

const btn = document.getElementById('btn');
const calc = document.getElementById('calc');

function add() {
  const num1 = parseInt(document.getElementById('num1').value);
  const num2 = parseInt(document.getElementById('num2').value);
  const result = document.getElementById('result');

  if (num1 && num2 !== NaN) {
    calc.addEventListener('click', () => {
      let sum = num1   num2;
      result.value = sum;
      return false;
    });

  } else {
    alert("Enter Valid Number");
  }
}

btn.addEventListener('click', () => {
  num1.value = " ";
  num2.value = " ";
  result.value = " ";
});
<form id="adder" onsubmit="return add();">
  <input type="text" name="num1" id='num1' placeholder="enter number">
  <input type="text" name="num2" id='num2' placeholder="enter number">

  <button id="calc" type="button">Add</button>
  <input type="text" name="num3" id="result" readonly placeholder="Result">

  <button type="button" id="btn">Clear</button>
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You need to create addEventListener of calc button outside add(); and call add(); into event;

const btn = document.getElementById('btn');
const calc = document.getElementById('calc');

function add() {
  const num1 = parseInt(document.getElementById('num1').value);
  const num2 = parseInt(document.getElementById('num2').value);
  const result = document.getElementById('result');
  if (num1 && num2 !== NaN) {
    let sum = num1   num2;
    result.value = sum;
    return false;

  } else {
    alert("Enter Valid Number");
  }
}
calc.addEventListener('click', () => {
  add();
});
btn.addEventListener('click', () => {
  num1.value = " ";
  num2.value = " ";
  result.value = " ";
});
<form id="adder" onsubmit="return add();">
  <input type="text" name="num1" id='num1' placeholder="enter number">
  <input type="text" name="num2" id='num2' placeholder="enter number">

  <button id="calc" type="button">Add</button>
  <input type="text" name="num3" id="result" readonly placeholder="Result">

  <button type="button" id="btn">Clear</button>
</form>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

onsubmit doesn't fire because you didn't add a submit button, anyway that method doesn't work because you add an eventListener that will work after press submit.

  • Related