Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input.value returns NaN

Tags:

javascript

If someone can help me because I have no clue why I always have NaN in console. Everything seems to be ok. The code should get value of input and do simple calculations. Unfortunetely I've received NaN so I decided to use console.log to explore values and it explained me that value of every input is NaN. I think that solution is obvious but I am newbie and I have been wondering what is my mistake for 2 hours.

  <div id="wrapper">
        <section>
            <h2>Give width of tile</h2>
            <input id =width type="number"/>
            <h2>Give height of tile</h2>
            <input id =height type="number"/>
            <h2>Price of one tile</h2>
            <input id =price type="number"/>
        </section>
        <section>
            <h2>Surface</h2>
            <input id = "surface" type="number"/>
            <button id="calculate">Calculate</button>
        </section>
        <section>
            <p>The price is:</p>
            <div id="result">

            </div>
        </section>

    </div>   

    <script src="main.js"></script>

JS

   document.addEventListener("DOMContentLoaded", function(event) { 

    var width = parseInt(document.getElementById("width").value);
    var height = parseFloat(document.getElementById("height").value);
    var price= parseFloat(document.getElementById("price").value);
    var surface= parseFloat(document.getElementById("surface").value);
    var calculate= document.getElementById("calculate");
    var result= document.getElementById("result");



    calculate.addEventListener("click", function(){

        console.log(width);
        console.log(height);
        console.log(price);
        console.log(surface);

        var surfaceTile = parseFloat(width * height);
        price = parseFloat(price).toFixed(2);

        var numberTiles = (Math.ceil(surface/surfaceTile)).toFixed(2);
        var cost = numberTiles * price;
        result.innerText = cost;
    });

});
like image 433
Tergo Avatar asked Feb 14 '26 09:02

Tergo


1 Answers

The fields don't have value attributes, so when you read them (which is as soon as the DOM is ready) their values are all "".

When you try to convert "" into a Number, you get NaN because they are not numbers.

Don't try to read the value until the value has been entered (e.g. inside the function that handles the click event).

like image 140
Quentin Avatar answered Feb 16 '26 22:02

Quentin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!