Stuck in build-a-real-time-counter

Hi everyone. I’m stuck on the build a real time counter challenge. I have been able to fulfill all user stories except for:

If character count is greater than or equal to 50, the user shouldn’t be able to enter more characters.

This is my current HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Real Time Counter</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
<h1>Count My Characters! &#128512;</h1>

<textarea id="text-input"></textarea>
<p id="char-count">Character Count: 0/50</p>

<script src="script.js"></script>
</body>
</html>

And my JS:

const textBox = document.getElementById("text-input"); // variable for textarea
const resultText = document.getElementById("char-count"); // variable for output character count

textBox.addEventListener('input', () => {
  let userInput = textBox.value;
  let chars = userInput.length; // counts characters
  let limit = 50 // defines limit
  resultText.innerHTML = `Character Count: ${chars}/50`; // updates characters in output
  if (chars >= limit) {
    resultText.classList.add("red"); // changes output to red
    let firstFifty = textBox.value.substring(0,49); // extracts first 50 characters
    textBox.value = firstFifty; // resets text inside textarea to first fifty characters
    resultText.innerHTML = `Character Count: ${limit}/50`; // displays only up to 50 characters
  }
})

I’ve tried adding the maxlength attribute and adding the disabled attribute on the textbox. After noticing it is still possible to go beyond 50 characters by copying/pasting, I am now resetting the textarea content to the first 50 characters. Still, I can’t pass.

Any ideas? Thanks in advance.

Hello, Please post the link to the challenge.

Build a Real Time Counter: Build a Real Time Counter | freeCodeCamp.org

You have an Off-By-One Error
check console.log(firstFifty.length)

1 Like

That did it! Thank you!

Hi, can you explain what the console log did in this case, I`m just trying get the solution. Thx

please create your own topic for asking help

console.log prints the value of things in the console, it shows the value of firstFifty.length

1 Like

If you’re saying you want to understand what caused the off-by-one error, take a look at this explanation of substring() parameters:
String.prototype.substring() - JavaScript | MDN

1 Like

It didn’t do anything for the exercise itself. It was simply a step I should have taken to detect the bug in my original code that was not letting me pass.

1 Like

I console logged and it came back as not defined so I guess that worked.

you need to add the console.log(firstFifty.length) in the right place to see the value, it needs to be a place where firstFifty is defined

Alright, I’m going to give that a try. Thank you