Teal Teal - 2 months ago 6
Javascript Question

JavaScript Code Problems

ISSUE HAS BEEN RESOLVED! Thanks to mortezaT.

Answer

HTML input values types are string so to calculate rounded value of them you should convert them to number. there is many ways to convert them to number like call the Number with the string value or adding a plus sign (+) (or division or multiply):

var val = document.querySelector('#val');
var k2l = document.querySelector('#kg-to-lb');
var l2k = document.querySelector('#lb-to-kg');
var res = document.querySelector('#result');

//displaing reported values...for kg to pounds
var report1 = function(kilogram, pound) {
  result.innerHTML =
    kilogram + "kg = " + pound + "lb";
};


//displaing reported values...for pounds to kilograms
var report2 = function(pound, kilogram) {
  result.innerHTML = pound + "lb = " + kilogram + "kg";
};

k2l.addEventListener('click', function(e) {
  var kilogram = val.value;
  var pound = Math.round(kilogram * 2.2);
  report1(kilogram, pound);
});
l2k.addEventListener('click', function(e) {
  var pound = val.value;
  var kilogram = Math.round(pound / 2.2);
  report2(pound, kilogram);
});
value
<input id="val" type="number" />

<button id="kg-to-lb">kg 2 lb</button>
<button id="lb-to-kg">lb 2 kg</button>
<div id="result"></div>