0

I am not really sure what is happening but I want to write a program that puts commas in a number you input, but when I run it and input a number the output is blank. Can anyone help???

HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="script.js" defer></script>
  </head>
  <body>
    <h1>Enter your number below:</h1>
    <input type="text" placeholder="Right here" id="number">
    <button id="submitButton">Add commas</button><br>
    <h1 id="numberWithCommas">0</h1>
  </body>
</html>

JavaScript:

const number = document.querySelector("#number").value;
let answerElement = document.querySelector("#numberWithCommas")
const button = document.querySelector("#submitButton");

button.addEventListener("click", () => {
    answerElement.textContent = number.toLocaleString();
})

I am not really sure what is happening so I can't tell you much. Sorry.

Chris A.
  • 15
  • 2

1 Answers1

0

let answerElement = document.getElementById('numberWithCommas');
const button = document.getElementById('submitButton');

button.addEventListener("click", () => {
    const number = document.getElementById('number').value;

    answerElement.textContent = Number(number).toLocaleString();
})

You need to use Number(x) for it to work. Also, the variable number should be defined after the button press, each time.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
  • I'm sorry. But, for ` –  Feb 14 '22 at 23:41
  • Absolutely not. Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. Please _never_ suggest or encourage these attributes. The last browser that still needs them reached end of life nearly two decades ago. – Sebastian Simon Feb 14 '22 at 23:41
  • ok, I don't want to argue about personal opinion, but I edited the answer. it should work now. –  Feb 14 '22 at 23:53