JSFiddle - React, Tailwind, and code Playground

by mori57

HTML

<h1>My First JavaScript</h1>

<p>Please input a number.</p>
<input id="demo" type="text">
<input id="demo1" type="text">
<input id="demo2" type="text" value="">
<button type="button" onclick="myFunction()">Click Me!</button>

JavaScript

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;
}