Alekss
Alekss

Reputation: 13

How to fix these undefined values?

So I have a function that I need to pass 3 values, but my values are allways 0 if I don't enter them, and undefined if enter them. How to fix this issue?

<!DOCTYPE html>
<html>
<head>
    <title>Calculate Area</title>
</head>
<body>
    <h4>Enter Dimensions</h4>
    <input id="a" type="text" name=""><br>
    <input id="b" type="text" name=""><br>
    <input id="c" type="text" name=""><br>
    <input type="button" onclick="calculate()" value="Calculate">

    <div id="output"></div>


    <script>

        var a = Number(document.querySelector('#a').value);
        var b = Number(document.querySelector('#b').value);
        var c = Number(document.querySelector('#c').value);

        function calculate(a, b, c){
            //console.log(a);
            //console.log(b);
            //console.log(c);
            return 2*(a*b + a*c + b*c);
        }

        var p = calculate(a, b, c);

        document.querySelector('#output').innerHTML = `<h4>Area = ${p}</h4>`;



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

Upvotes: 0

Views: 148

Answers (2)

Adnan Toky
Adnan Toky

Reputation: 1943

You are collecting the value of a, b and c at the beginning of the program. At first, the input boxes don't have any value, so the value of a, b and c is undefined. So collect the value when the submit button is clicked.

Try this approach:

function calculate(){
    var a = Number(document.querySelector('#a').value);
    var b = Number(document.querySelector('#b').value);
    var c = Number(document.querySelector('#c').value);

    var p = 2*(a*b + a*c + b*c);

    document.querySelector('#output').innerHTML = '<h4>Area = ${p}</h4>';
}

Upvotes: 0

lankovova
lankovova

Reputation: 1426

You need to get value from elements and set it to #output element each time calculate function is called. Check out my solution below.

var aElement = document.querySelector('#a');
var bElement = document.querySelector('#b');
var cElement = document.querySelector('#c');
var outputElement = document.querySelector('#output');

function updateArea () {
    var a = Number(aElement.value);
    var b = Number(bElement.value);
    var c = Number(cElement.value);
    
    var res = calculate(a, b, c);
    
    outputElement.innerHTML = `<h4>Area = ${res}</h4>`;
}

function calculate (a, b, c) {
    return 2*(a*b + a*c + b*c);
}
<h4>Enter Dimensions</h4>
<input id="a" type="text" name=""><br>
<input id="b" type="text" name=""><br>
<input id="c" type="text" name=""><br>
<input type="button" onclick="updateArea()" value="Calculate">
<div id="output"></div>

Upvotes: 2

Related Questions