Reputation: 65
I am trying to recreate a garment measurement chart I've seen, but in pure Javascript. I'm having trouble figuring out how to grab the number value in innerhtml and multiply/divide it by * 2.54. Additionally, I'd like to add "cm" or "in" at the end of the number to indicate the measurement system.
https://jsfiddle.net/kud8sj7w/5/
<div id="xs-sizes">
<li class="measurement" style="left: 15%; top: 33%;">
63.5
</li><li class="measurement" style="left: 48%; top: 16%;">
43.5
</li><li class="measurement" style="left: 48%; top: 79%;">
50.5
</li><li class="measurement" style="left: 48%; top: 50%;">
43
</li><li class="measurement" style="left: 83%; top: 62%;">
64.5
</li>
function convert() {
var measurements = document.getElementsByClassName("measurement");
for(var i = 0; i < measurements.length; i++){
measurements[i].innerHTML = valNum * 2.54;
}
}
Upvotes: 5
Views: 1046
Reputation: 66
So for measurements[i].innerHTML = valNum * 2.54;
, valNum
is undefined. Look at convert()
there's no parameters. When it's called it multiplies by valNum
which is undefined
.
Think about what valNum
should equal to or what 2.54
should be operating on. I hope that helps. Also to string the cm/unit
, you can just concatenate but get the result first.
Upvotes: 3
Reputation: 86
You need to store the current state to know whether you need to convert or not. In your case, initially 'CM'
let cur_measurement = 'CM';
function convert() {
let measurements = document.getElementsByClassName("measurement");
let CM = document.querySelector('input[value="CM"]');
let IN = document.querySelector('input[value="IN"]');
let ratio = 0;
if(CM.checked && cur_measurement != 'CM'){
ratio = 2.54;
cur_measurement = 'CM';
} else if (IN.checked && cur_measurement != 'IN' ){
ratio = 1/2.54;
cur_measurement = 'IN';
}
for (var i = 0; i < measurements.length; i++) {
let cur_val = parseFloat(measurements[i].innerText);
measurements[i].innerText = Math.round(cur_val * ratio * 10) / 10;
}
}
Upvotes: 4