简体   繁体   中英

Can't figure out whats wrong in the javascript portion of code

document.getElementById('go').onclick = function() {

    var data = document.getElementById('number1').value;

    data = parseFloat(number1);

    var data = document.getElementById('number2').value;

    data = parseFloat(number2);

    var total = number1 + number2;

    document.getElementById('result').value = total;
};

You store the value after the parseFloat into wrong variable. You're basically just overriding the same variable data , and also you did not initialize variables number1 and number2 .

It should be like this:

document.getElementById('go').onclick = function() {

    var number1 = document.getElementById('number1').value;

    number1 = parseFloat(number1);

    var number2 = document.getElementById('number2').value;

    number2 = parseFloat(number2);

    var total = number1 + number2;

    document.getElementById('result').value = total;
};
  1. You are using variables that haven't been defined ( number1 && number2 ).
  2. That's not how parseFloat works. parseFloat take an argument (a string) and return a float if any.

Try this:

document.getElementById('go').onclick = function() {
    var data = document.getElementById('number1').value;

    var number1 = parseFloat(data); // parse the data and store the result in number1

    data = document.getElementById('number2').value; // no need to redeclare data

    var number2 = parseFloat(data); // parse the data and store the result in number2

    var total = number1 + number2;

    document.getElementById('result').value = total;
};

You are doing the "parseFloat" function on the document's input element whose ids are "number1" and "number2" instead of the actual values that you typed into them. You can't usefully turn a document's input textbox into a float. Also, you use the variable "data" twice, but you want to store the value of whatever is typed into the number1 box, and add that to whatever is typed into the number2 box, and add both those up so you need two variables. Then oyu can add those two up and assign that to the "total" variable.

I assume your HTML is similar to this:

 <input id="number1" type="text" /> <br><input id="number2" type="text" /> <br><input id="go" type="button" value="Add Up" /> <br><input id="result" type="text" />

 document.getElementById('go').onclick = function () { var number1Value = document.getElementById('number1').value; number1Value = parseFloat(number1Value); var number2Value = document.getElementById('number2').value; number2Value = parseFloat(number2Value); var total = number1Value + number2Value; document.getElementById('result').value = total; };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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