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! 😀</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.