You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Description of Issues :
The original JavaScript code incorrectly counts characters instead of words. It also does not handle cases where the user enters only spaces. Additionally, there was an unused variable, and some improvements can be made for accessibility and user experience.
corrected code :
const text = document.querySelector('#text');
const ans = document.querySelector('#ans');
const button = document.querySelector('#button');
const words = () => {
if (!text.value.trim()) { // Check for empty or whitespace-only input
ans.innerHTML = 'Please Enter Something to count';
} else {
const wordCount = text.value.trim().split(/\s+/).length; // Split by spaces and count
ans.innerHTML = wordCount;
}
}
https://github.com/DhanushNehru/Hacktoberfest2024/blob/main/JavaScript/countWords.html
Description of Issues :
The original JavaScript code incorrectly counts characters instead of words. It also does not handle cases where the user enters only spaces. Additionally, there was an unused variable, and some improvements can be made for accessibility and user experience.
corrected code :
const text = document.querySelector('#text');
const ans = document.querySelector('#ans');
const button = document.querySelector('#button');
const words = () => {
if (!text.value.trim()) { // Check for empty or whitespace-only input
ans.innerHTML = 'Please Enter Something to count';
} else {
const wordCount = text.value.trim().split(/\s+/).length; // Split by spaces and count
ans.innerHTML = wordCount;
}
}
button.addEventListener('click', words);
text.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
words();
}
});
The text was updated successfully, but these errors were encountered: