How do I add numbers in innerHTML?

Asked

Viewed 196 times

-3

The code is not adding, just joining (concatenating*) the numbers

var media = "";
var media2 = "";
var media3 = "";
var media4 = "";

function myFunction(){

media = Number(document.getElementById("vnota").value);
media2 = Number(document.getElementById("vnota2").value);
media3 = Number(document.getElementById("vnota3").value);
media4 = Number(document.getElementById("vnota4").value);

document.getElementById("notas").innerHTML = "A sua nota final é: " + media + media2 + media3 + media4;


}

  • "Putting together" you mean "concatenating", it’s not?

  • Try to put the sum in parentheses ("A sua nota final é: " + (media + media2 + media3 + media4)). If not you can add before and save to a variable, total, for example

  • It worked, thanks bro! <3

2 answers

1


var media = "";  //Apenas uma variável é necessária, vc só precisa ir 
                 //somando a cada nova nota;

function myFunction(){

media = Number(document.getElementById("vnota").value);
media += Number(document.getElementById("vnota2").value);
media += Number(document.getElementById("vnota3").value);
media += Number(document.getElementById("vnota4").value);

document.getElementById("notas").innerHTML = "A sua nota final é:" +media ;


}

-1

Can create a total variable the code would look like this total = (media + media2) + media3 + media4 and the total variable has to be declared within the Myfunction dps only writing it in innerHTML would save that amount of media in innerHTML.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.