I am trying to make a home assignment on javascript. In the assignment I am asked to input a number and then I have to make some mathematical operations with that number. In the end I have to display lines with these mathematical operations on the screen. My problem is that I don´t get how to display several lines using innerhtml.
I tried to make several ids for the document.getElementbyid, but it didn´t help.
<!DOCTYPE html>
<html>
<body>
<h2>Oppgave 1 - Lek med tall</h2>
<p>Input a (one) number and click the button:</p>
<input id="tall" value="1" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var t;
t= Number(document.getElementById("tall").value);
var c=t/2
var b=t*2
var v=t*3
var w=t**2
document.getElementById("demo").innerHTML = "Halfpart of the number is: "+c;
document.getElementById("demo").innerHTML = "The double of the number is: "+b;
document.getElementById("demo").innerHTML = "The triple of the number is: "+b;
}
</script>
</body>
</html>
Halfpart of the number is: The double of the number is: The triple of the number is:
Every time you assign a new value with innerHTML=
, you are overwriting the previous value. If you want all of that text in the "demo" element, but need to split that process over three lines, try the += operator.
There are several techniques to show different lines. Try making three different p elements ("demo1", "demo2", "demo3"), or perhaps add a <br>
tag at the end of the first two lines.
document.getElementById("demo").innerHTML = "Halfpart of the number is: "+c;
document.getElementById("demo").innerHTML += "The double of the number is: "+b;
document.getElementById("demo").innerHTML += "The triple of the number is: "+b;