Multiply two numbers javascript?



 function multiplynums (num1,num2){
  var thenumber1 = Number(num1);
  var thenumber2 = Number(num2);
  var theanswer =  thenumber1 * thenumber2;
  document.getElementById("answer").innerHTML= theanswer.tostring(); 



<input type= "text" id="txtnumber1">
<input type= "text" id="txtnumber2">
<input type= "text" id="txtanswer">
<input type="button" id="btnEnter" value="Enter"  onclick="multiplynums(txtnumber1.value,txtnumber2.value")>       
    <p> the Answer is:</p> 
    <p id="Answer"></p>




This, and the other one are element id’s which values are not directly readable. Both of the elements need to be queried for their value.

Try calling the function with no arguments and inside the function get and cache the two elements’ values.


Another note is the capitalization, assuming you referred to the same id? But have a look at this:


//but near the end, your id
<p id="Answer"></p>



Below is a refactored form of your app for you to study and glean from what you can…


App UX
<!DOCTYPE html>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Multiply Numbers</title>
    div {
      width: 40%;
      text-align: center;
      margin: 0 auto;
    input {
      text-align: center;
      <input type="text" id="num1" size="8"> *
      <input type="text" id="num2" size="8"> =
      <input type="text" id="answer" readonly="readonly" size="10">
    const num1 = document.querySelector("#num1");
    const num2 = document.querySelector("#num2");
    const answer = document.querySelector("#answer");
    const button = document.querySelector('button');

    const multiplynums = () => {
      answer.value = (+num1.value * +num2.value).toString();

    button.addEventListener('click', multiplynums);


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.