Skip to content Skip to sidebar Skip to footer

How To Get Values In Span Tag From Js

I am trying to make a BMI Calculator using HTML. The inputs come from text fields. I am making some calculation with them in a Javascript function. I want to get the calculated val

Solution 1:

Edit: As it was pointed out, FF doesn't like innerText, so I'm replacing to innerHTML which in this particular case doesn't not change the overall functionality of the script.

You can get the 2nd span and pass the value directly to innerHTML like this:

document.getElementsByTagName('span')[1].innerHTML= 'the result';

Note: Consider using and id or class so you can find the exact element you need to change instead of retrieving several elements of that type (in this case span). If you had an id, it would be like this:

document.getElementById('the id goes here').innerHTML= 'the result';

Edit2: This edit was made after the OP changed his question It got really confusing now that I'm seeing your code. I've written this fiddle so you can see it working

Solution 2:

If you have a variable like calcResult, you can do:

document.getElementById('spanId').innerHTML += calcResult;

Of course, that only works once. If you do it again, you'll have two results in the span. If you want to be able to change the result if the form fields change, I'd try:

<span id="calc">Your calculation result = <span></span></span>

var result = 12;
document.getElementById('calc').getElementsByTagName('span')[0].innerHTML = result;

Solution 3:

Have you tried Jquery ?

$("span").next().text("Your Result");

OR

$("span").eq(1).text("Your Result");

To do a better code, put a ID in your component.

Solution 4:

You can use document.writeln to get your result. check out the fiddle on http://jsfiddle.net/CmVww/ to play with it. Below are the results.

<divid="start"><spanid="one"class="sText">Your Calculation Results is = </span><spanid="two"class="result"><scripttype="text/javascript">var tst = 'I want the result here';
  document.writeln(tst);
</script></span>

Solution 5:

var bmi = weight / (heightInMeter * heightInMeter);
document.getElementById('ID_bmiResult2').innerHTML= bmi;

Post a Comment for "How To Get Values In Span Tag From Js"