WannaBeCoder
WannaBeCoder

Reputation: 1282

how to sum two elements in javaScript

this is my first JavaScript program and I hit my first road block. can anyone tell me where am I doing wrong. I want to get the sum of first two boxes on third box after clicking the button

 <!DOCTYPE html>
   <html>
   <body>

   <h1>My First JavaScript</h1>

   <p>Please input a number.</p>



   <script>
   function myFunction()
   {
    var x=document.getElementById("demo").value;
    var y=document.getElementById("demo1").value;
    var z=parseInt(x)+parseInt(y);

     document.getElementById("demo2").value=Z;
   }
  </script>

   <input id="demo" type="text">
   <input id="demo1" type="text">
   <input id="demo2" type="text" value="">

   <button type="button" onclick="myFunction()">Click Me!</button>

Upvotes: 1

Views: 2468

Answers (3)

Jason M. Batchelor
Jason M. Batchelor

Reputation: 2951

Also, in addition to the case-sensitivity issue that others have called out, your code is prone to another issue. It's always a good idea to test that you have a valid reference to an object before you attempt to call a method on that object:

function myFunction() {
    // First, get a reference to the form fields
    var demo = document.getElementById("demo");
    var demo1 = document.getElementById("demo1");
    // next, test to see if the reference exists with an if construct ...
    var x = 0;
    if(demo !== null){
        x = parseInt(demo.value, 10);
    }
    // you could also use a ternary operator, like this, to do the same thing but 
    // with slightly more compact code...
    var y = (demo1 !== null) ? parseInt(demo1.value, 10) : 0;
    var z = x + y;

    document.getElementById("demo2").value = z;
}

Lastly, as a matter of small import, it's best not to use single-letter variable names in general practice. It's not bad for learning early-on, but getting into the habit of making variable names relevant and understandable will help you a lot in the long run.

Good luck and welcome to the wide world of Javascripting!

Upvotes: 1

Suman Bogati
Suman Bogati

Reputation: 6351

try this, you are putting Z instead of z as result.

 <!DOCTYPE html>
   <html>
   <body>

   <h1>My First JavaScript</h1>

   <p>Please input a number.</p>



   <script>
   function myFunction()
   {
    var x=document.getElementById("demo").value;
    var y=document.getElementById("demo1").value;
    var z=parseInt(x)+parseInt(y);

     document.getElementById("demo2").value=z;
   }
  </script>

   <input id="demo" type="text">
   <input id="demo1" type="text">
   <input id="demo2" type="text" value="">

   <button type="button" onclick="myFunction()">Click Me!</button>

Upvotes: 3

Matt
Matt

Reputation: 20796

JavaScript is case-sensitive:

document.getElementById("demo2").value=Z; // <-- Change to lower-case z

Upvotes: 7

Related Questions