Output not expected when send to HTML

What’s wrong with my code? When I do a console.log() I get the expected output, which converts arabic numeral to a roman numeral. But when I send it to the HTML it does not recognize the function, only the dictionary inside the function.
CODEPEN:

Javascript:

const inputNumber = document.querySelector(".input-number")
const romanNumber = document.querySelector(".roman-number")

function convertToRoman(num) {
  const romanNum = {
    1: "I",
    4: "IV",
    5: "V",
    9: "IX",
    10: "X", 
    40: "XL",
    50: "L",
    90: "XC",
    100: "C",
    400: "CD",
    500: "D", 
    900: "CM", 
    1000: "M", 
  }

  let romanized = ''
  const romanKeys = Object.keys(romanNum).reverse()

  // if (isNaN(num)) return "Is not a number"

  romanKeys.forEach(key => {
    while(key <= num) {
      romanized += romanNum[key]
      num -= key
    }
  })
  return romanized
}

// Good Output!!!
console.info(convertToRoman(2))
console.info(convertToRoman(3))
console.info(convertToRoman(8))

inputNumber.addEventListener("change", (e) => {
  const romanNumberResult = convertToRoman(e.target.value)
  // - - -  Bad Output  - - -
  romanNumber.innerText = romanNumberResult;
})

Capture:

Because it’s not a number you’re getting from the input, it’s a string. "9" comes after "1". And after "10", or "100", or "1000". And your function requires numbers for it to work, for it to actually generate the correct answer

Yes, you right!
Already fixed:

inputNumber.addEventListener("change", (e) => {
  const romanNumberResult = convertToRoman(Number(e.target.value))
  romanNumber.innerText = romanNumberResult;
})

Thanks tons!

1 Like