Print Variable Value

Print Variable Value
0

#1

This is not printing the result. What am I missing here?


function calculate() {
		var age = document.getElementById("age").value;	
		var urea = document.getElementById("urea").value;
		document.getElementById("result").innerHTML = age + urea;
    
	}

  
< input id="age" type="number"/>
 < input id="urea" type="number"/>
 
 < button onClick="calculate()">Calculate< /button>
  
 < p id="result"/>< /p>

#2

Can you post the html too? Or link to a pen? It’s not clear to me what you’re trying to do here.


#3

I have the html in the question but when I post it disappears… (obviously very new here)


#4

OK, it;s there now. When I run it, it concats the two inputs fine - it assumes that they are strings. Were you looking to get it to add the numbers? Then you should put a + in front of the values to force them to numbers:

function calculate() {
    var age = +document.getElementById("age").value;	
    var urea = +document.getElementById("urea").value;
    document.getElementById("result").innerHTML = age + urea;
}

It would be easier to answer your question if you were more clear about what you were trying to do.

Also, code looks better if you wrap it in a “preformatted text” style.

Also be careful with those extra spaces inside your element tags - those can cause problems.Preformatted text


#5

I should include the html too:

<body>
  <input id="age" type="number"/>
  <input id="urea" type="number"/>

  <button onClick="calculate()">Calculate</button>

  <p id="result"/></p>
</body>

#6

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#7

This code runs fine for me, albeit as a string concatenation instead of numeric addition. Like ksjazzguitar said, if you want to calculate the result of the input summed together, you’ll need to “cast” the input to a number.

Do keep in mind that if you are using something like jsfiddle to do this, the console will print out “calculate is undefined” unless you set the “Load Type” to "No wrap - in ". This error would mimic what you are describing (nothing being printed out).