Build a Roman Numeral Converter

I don’t understand why my code doesn’t run 2 if conditions:

HTML:
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="styles.css"/>
  </head>
  <body>
    <h3>ROMAN CONVERTER</h3>
    <input type = "number" id = "number"></input>
    <button id = "convert-btn" onclick = "convertButton()">Convert</button>
    <div id = "output"></div>
    <script src="script.js"></script>
  </body>
</html>

JavaScript:

const convertBtn = document.getElementById("convert-btn"); // Const button element
const numberInput = document.getElementById("number");
const alphanumericChars= /[a-zA-Z0-9]/g; // [] regex character class and global flag
const output = document.getElementById("output");
const n = numberInput.value;

function convertButton() {
  if (n === "") {
    output.innerHTML = "Please enter a valid number";
  } 
    else if (n < 1) {
      output.textContent = "Please enter a number greater than or equal to 1";
    }
    else if (n > 3999) {
      output.textContent = "Please enter a number less than or equal to 3999";
    }
} 

convertBtn.addEventListener("click", convertButton);

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

this line of code is in the global scope.
Therefore n will always be empty.
You need to move it to the local scope of the function that runs on the click.

1 Like

Thank you, now I understand.

1 Like