Home > Enterprise >  Javascript How do I display an error message?
Javascript How do I display an error message?

Time:10-31

everyone, I'm fairly new to Javascript especially using the DOM so now came the time where I decided to put everything i've been learning to work, but now, I'm stuck on a problem.

Basically, i'm trying to display an error message once the user exceeds 180 characters in the textArea, however, I can't seem to output the expected result.

Using the if statement and textContent i am unable to get solve this. What am I doing wrong? please help and thanks.

here is the code:

<html>
 <head>
   <title>JavaScript &amp; jQuery - Chapter 6: Events - Keypress</title>
 </head>
 <body>
   <div id="page">
     <h1>List King</h1>
     <form id="messageForm">
       <h2>My profile</h2>
       <textarea id="message"></textarea>
       <div id="charactersLeft">180 characters</div>
       <div id="feedback"></div>
       <div id="lastKey"></div>
     </form>
   </div>
   <script src="key.js"></script>
 </body>
</html> 


var el;

function charCount(e) {
   var textEntered, charDisplay, counter, lastKey, feedback;
   textEntered = document.getElementById('message').value;
   charDisplay = document.getElementById('charactersLeft');
   counter = (180 - (textEntered.length));
   charDisplay.textContent = counter;
   lastKey = document.getElementById('lastKey');
   lastKey.textContent = ' Last key in ASCII code: '   e.keyCode;

   // Displays error message
   var feedback = document.getElementById('feedback');

   if(counter.value.length <= feedback) {
   feedback.textContent = ' characters must be 180 or less'; }
   else {
       feedback.textContent = '';
   }

   }


el = document.getElementById('message');
el.addEventListener('keyup', charCount, false); 

CodePudding user response:

You are trying to compare a path that doesn't exist in a number (counter.value.length) to a dom element (feedback = document.getElementById()) at if(counter.value.length <= feedback).

Your counter is a number already counter = 180 - textEntered.length.

You probably want to set a var maxLength = 180 as well, then:

if (counter <= maxLength) {
  feedback.textContent = ' characters must be 180 or less'
} else {
  feedback.textContent = ''
}

  • Related