简体   繁体   English

Input.value返回NaN

[英]Input.value returns NaN

If someone can help me because I have no clue why I always have NaN in console. 如果有人可以帮助我,因为我不知道为什么我总是在控制台中使用NaN。 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. 不幸的是,我收到了NaN,所以我决定使用console.log探索值,它向我解释了每个输入的值都是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 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;
    });

});

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 "" . 字段没有value属性,因此当您读取它们(DOM准备就绪时)时,它们的值都是""

When you try to convert "" into a Number , you get NaN because they are not numbers. 当您尝试将""转换为数字时 ,会得到NaN因为它们不是数字。

Don't try to read the value until the value has been entered (eg inside the function that handles the click event). 在输入值之前,请勿尝试读取该值(例如,在处理click事件的函数内部)。

Add all the declaration inside the click event not with Global .Because document load its empty value so only you get NaN .And add or(|) condition ,if the variable is NaN its set as a Zero by default => value|0 将所有声明添加到click事件中,而不要使用Global。因为文档加载了空值,所以只有NaN。并添加or(|)条件,如果变量为NaN ,则默认将其设置Zero => value|0

 document.addEventListener("DOMContentLoaded", function(event) { calculate.addEventListener("click", function() { var width = parseInt(document.getElementById("width").value|0); var height = parseFloat(document.getElementById("height").value|0); var price = parseFloat(document.getElementById("price").value|0); var surface = parseFloat(document.getElementById("surface").value|0); var calculate = document.getElementById("calculate"); var result = document.getElementById("result"); 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; }); }); 
 <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> 

add the below lines of code in calculate.addeventlisterer. 将以下代码行添加到calculate.addeventlisterer中。 The width, height, etc will be calculated at the time of dom is ready. 宽度,高度等将在dom准备就绪时进行计算。 By that time no values present in the textboxes. 到那时,文本框中没有任何值。 Hence it returns NAN 因此它返回NAN

    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");

Best approach is to create an update function 最好的方法是创建更新功能

var update = function(elm,id){
        if(id=='width'){
           width = parseInt(elm.value);
        }else if(id=='height'){
           height= parseFloat(elm.value)
        }else if(id=='price'){
           price = parseFloat(elm.value)
        }else if(id=='surface'){
           surface= parseFloat(elm.value)
        }
     }

and call that function onchange event of input fileds 并在输入字段中调用该函数的onchange事件

   <input id=width type="number" onchange="update(this,this.id)" />

Inside your click function make sure you have all defined before parsing 在click函数中,请确保在解析之前已定义所有内容

if(!width||!height||!price||!surface) return;

SNIPPET SNIPPET

 var width; var height; var price; var surface; var calculate; var result; var update = function(elm, id) { if (id == 'width') { width = parseInt(elm.value); } else if (id == 'height') { height = parseFloat(elm.value) } else if (id == 'price') { price = parseFloat(elm.value) } else if (id == 'surface') { surface = parseFloat(elm.value) } } document.addEventListener("DOMContentLoaded", function(event) { calculate = document.getElementById("calculate"); result = document.getElementById("result"); calculate.addEventListener("click", function() { if (!width || !height || !price || !surface) return; 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; }); }); 
 <div id="wrapper"> <section> <h2>Give width of tile</h2> <input id=width type="number" onchange="update(this,this.id)" /> <h2>Give height of tile</h2> <input id=height type="number" onchange="update(this,this.id)" /> <h2>Price of one tile</h2> <input id=price type="number" onchange="update(this,this.id)" /> </section> <section> <h2>Surface</h2> <input id="surface" type="number" onchange="update(this,this.id)" /> <button id="calculate">Calculate</button> </section> <section> <p>The price is:</p> <div id="result"> </div> </section> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM