Tell us what’s happening:
I can’t seem to figure out how to get the result to appear in the outputBox, when I console.log(convertToRoman)
, it shows me the correct answer. I think I just have to place the code in a different spot, but I have tried placing the whole function in the if…else statement of the addEventListener, and placing it above as well, but it still can’t get it to work
Your code so far
<!-- file: index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
<title>Roman Numeral Converter</title>
</head>
<body>
<h1 id="title">Roman Numeral Converter</h1>
<div class="enter-here">
<p class="instruction">Enter a Number</p>
<input id="number"></input>
<button id="convert-btn">Convert</button>
</div>
<div id="output"></div>
<script src="script.js"></script>
</body>
</html>
/* file: script.js */
const numberInput = document.getElementById("number");
const convertBtn = document.getElementById("convert-btn");
const outputBox = document.getElementById("output");
const romanNums = {
1: "I",
2: "V",
4: "IV",
5: "V",
9: "IX",
10: "X",
40: "XL",
50: "L",
90: "XC",
100: "C",
400: "CD",
500: "D",
900: "CM",
1000: "M"};
function convertToRoman(numberInput) {
let result = "";
const arabicNumbers = Object.keys(romanNums).reverse();
arabicNumbers.forEach(key => {
while (key <= numberInput){
result += romanNums[key];
numberInput -= key;
return result;
}
})
outputBox.classList.add("answer");
outputBox.innerText = result;
};
// output alerts
convertBtn.addEventListener("click", () => {
let numberInput = document.getElementById("number").value;
if (numberInput === ""){
outputBox.innerText = "Please enter a valid number";
outputBox.classList.add("wrong-answer");
} else if (numberInput <= -1) {
outputBox.innerText = "Please enter a number greater than or equal to 1";
outputBox.classList.add("wrong-answer");
} else if (numberInput > 3999){
outputBox.innerText = "Please enter a number less than or equal to 3999";
outputBox.classList.add("wrong-answer");
} else {
convertToRoman();
}
});
Your browser information:
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36
Challenge Information:
Build a Roman Numeral Converter Project - Build a Roman Numeral Converter