Chizbe Joe Chizbe Joe - 2 months ago 6
jQuery Question

Why isn't this meter working?

So I have this code (Fiddle):



(function() {
var meter = document.getElementById('somemeter');
var Likes = document.getElementById('likes');
var Dislikes = document.getElementById('dislikes');

meter.max = Likes.innerHTML + Dislikes.innerHTML;
meter.value = Likes.innerHTML - Dislikes.innerHTML;
})();

<div id="likes">500</div>
<div id="dislikes">50</div>
<meter value="10" min="0" max="1000" id="somemeter"></meter>





As you can see,
Likes.innerHTML
is
500
, and
Dislikes.innerHTML
is
50


For some reason, the
meter.max
doesn't work when I use
Likes.innerHTML
or
Dislikes.innerHTML
; however, when I substitute those in the
meter.max
for
500
and
50
, it does work.

Am I doing something wrong?

Answer

You need to convert the strings to numeric values for the math to work:

(function() {
  var meter = document.getElementById('somemeter');
  var Likes = document.getElementById('likes');
  var Dislikes = document.getElementById('dislikes');

  meter.max = Number(Likes.innerHTML) + Number(Dislikes.innerHTML);
  meter.value = Number(Likes.innerHTML) - Number(Dislikes.innerHTML);
})();

Fiddle