Oscar Andersson Oscar Andersson - 3 months ago 8
Javascript Question

Calculate the difference between number from user input

This should be a no brainer but i have no experience in Javascript and i can't see why this should not work.

<!doctype html>

<html lang="en">
<head>
<meta charset="utf-8">

<title>Undantag</title>
<p> STD: </p>
<input type="number" name="STD">
<p> STA: </p>
<input type="number" name="STA">
<p> ATD: </p>
<input type="number" name="ATD">
<p> ATA: </p>
<input type="number" name="ATA">


<button onclick="useUndantag()">Click me</button>


</head>

<body>
<script>
function useUndantag() {
var a = document.getElementsByName("STD");
var b = document.getElementsByName("ATD");
var c = document.getElementsByName("STA");
var d = document.getElementsByName("ATA");


if (a-b >1) {
alert("No undantag");
}
else if (d-c >2) {
alert ("No undantag");

else () {
alert ("NO EU FOR YOU!")

}

}
}

</script>
</body>
</html>


The problem is that i get no alert at all and i can't seem to figure out why. If anyone has any tips if would be very glad for any help i can get.

Answer

First of all, getElementsByName returns a collection of HTML elements. Use [0] to access the first element. Next, you must use parseFloat or parseInt to parse the inputs as integers/floats. Also, HTML code goes in the body tag unless you have scripts, links, meta, title, and other tags. Finally, you have an syntax error:

else () { }

Should not have parentheses. You're also missing a brace after the else if, remove a closing brace after the else. Here's a fixed snippet:

    function useUndantag()  {
        var a = document.getElementsByName("STD")[0].value; 
        var b = document.getElementsByName("ATD")[0].value;
        var c = document.getElementsByName("STA")[0].value;
        var d = document.getElementsByName("ATA")[0].value;

        if (parseInt(a) - parseInt(b) > 1) { //notice the use of parseInt, you can use parseFloat to deal with decimals
            alert("No undantag");
        } else if(parseInt(d) - parseInt(c) > 2) {
            alert("No undantag");
        } else { //Notice no parentheses and some more braces
            alert("NO EU FOR YOU!")
        }
    }
<p> STD: </p> <!-- HTML is in body tag !-->
<input type="number" name="STD">
<p> STA: </p>
<input type="number" name="STA">
<p> ATD: </p>
<input type="number" name="ATD">
<p> ATA: </p>
<input type="number" name="ATA">


<button onclick="useUndantag()">Click me</button>

Also, make sure you use .value to get the value.