简体   繁体   中英

How do you turn a string from an HTML file to a number?

I want to turn a string in an HTML document to a number, but if I try to use Number() or parseInt() with a document.getElementByID it turns to NaN (well I would think that too but I didn't know any other option). Here is a code example:

function together() {
let base = document.getElementById("Base");
let add = document.getElementById("Addition");
let sumshow = document.getElementById("Sum");
let sum = Number /*or parseInt*/(base) + Number /*or parseInt*/(add);
sumshow.innerHTML = sum;
} 

github repo if you want full thing: github.com/SupaSibs/Calculator-Supa

This is becouse you are getting the element instead of the content of the element, you need to get the value or the innerHTML, like this:

 //Input case
     let base = document.getElementById("Base").value;
 //Element case
     let add = document.getElementById("Addition").innerHTML;

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