-2

I am trying to show my output inside the third box but it shows the output in a separate page. How to solve that.

function mul(){
    var a=parseInt(document.getElementById("f_num").value);
    var b=parseInt(document.getElementById("s_num").value);
    var res= a*b;
    document.write(res);
}
function div(){
    var a=parseInt(document.getElementById("f_num").value);
    var b=parseInt(document.getElementById("s_num").value);
    var res= a/b;
    document.write();
}
<form>
  <input type="text" id="f_num" placeholder="Enter your first number"><br><br>
  <input type="text" id="s_num" placeholder="Enter your second number"><br><br>
  <input type="submit" value="Multiply" onclick="mul()">
  <input type="submit" value="Divide" onclick="div()"><br><br>
  <input type="text">
</form>
Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45

1 Answers1

0

Your problem consists of two parts:

You're submitting a form with the buttons you're using type="submit" and you're using a form. This will submit the form to a new page. You could lose the form tags and change the buttons to actual buttons.

You're also writing the result to the document, but not to an element. In the snippet below I've added the code to write the result to the input.

function mul() {
  var a = parseInt(document.getElementById("f_num").value);
  var b = parseInt(document.getElementById("s_num").value);
  var res = a * b;
  document.getElementById("answer").value = res;
}

function div() {
  var a = parseInt(document.getElementById("f_num").value);
  var b = parseInt(document.getElementById("s_num").value);
  var res = a / b;
  document.getElementById("answer").value = res;
}
<input type="text" id="f_num" placeholder="Enter your first number"><br><br>
<input type="text" id="s_num" placeholder="Enter your second number"><br><br>
<button type="button" onclick="mul()">Multiply</button>
<button type="button" onclick="div()">Divide</button><br><br>
<input type="text" id="answer">
Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45