Jump to content
Larry Ullman's Book Forums

Textarea - Character Count


Recommended Posts

Hello,

 

I am trying to implement this code into a php script. By itself on a separate page it works fine but wihint a php page I keep getting syntax errors.

 

Thanks,

 

Marie

 

<textarea name="description" id="description" rows="5" cols="40" value="sdf" onkeyup="getCharCount(50)" />
</textarea>
<div id="charCount"></div>
<script type="text/javascript">
function getCharCount(limit)
{
var tArea	    = document.getElementById("description"),
 countDisplay = document.getElementById("charCount");
 countRemains = limit - tArea.value.length
countDisplay.innerHTML = "Total characters : " + tArea.value.length + " Remaining: " + countRemains;
if (countRemains < 1) alert('Thats all folks');
}
</script>

Link to comment
Share on other sites

My guess is that you have multiple attributes with the ID "description" or "charCount". Other than that, there's really no reason for your code to suddenly not work when you move it over to a script with other PHP/HTML.

 

Some other things to note:

1) You might want to add the maxlength attribute to the text area. It's only supported in HTML5, but comes in handy as a way to avoid passing the limit (see 2) next).

 

2) When you only use the onkeyup event, a user could easily hold down one key and pass the limit (as the onkeyup event would technically not fire until they release that one key). The maxlength attribute noted in 1) will stop this in HTML5 browsers, but not in older browsers like IE6/IE7.

For this reason, the onkeydown event is preferable. The one problem with the onkeydown event is that it doesn't capture the key you just pressed.

I looked into this issue a bit, and it seems like the best solution is to calculate the number of (remaining) characters for both the onkeydown and onkeyup events.

 

3) If the user is using an old browser, they can still pass the limit unless you add some more JS to actually truncate a string/stop them from typing any more characters when they reach the limit. Note that this requires some additional code.

 

4) If a user has JS disabled, all of the above points are moot. As such, you should have a non-JS warning about the character limit and always check the length on the PHP side as well.

 

Hope that helps.

Link to comment
Share on other sites

Hello,

 

Thanks for your suggestions. I have done quite a lot of experimenting but keep getting the same error.

 

 

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /page.php on line 367

 

Line 367 would be the following: if (countRemains < 1) alert('Thats all folks');

 

Following is the code in the forms_functions.inc.php

 

} elseif ($type == 'textarea') { // Create a TEXTAREA.

 // Display the error first:
 if (array_key_exists($name, $errors)) echo ' <span class="error">' . $errors[$name] . '</span>';
 // Start creating the textarea:

 echo '<textarea name="description" id="description" rows="5" cols="40" value="<? =$row[7] ?>"onkeyup="getCharCount(50)"';

 // Add the error class, if applicable:
 if (array_key_exists($name, $errors)) {
  echo ' class="error">';
 } else {
  echo '>'; 
 }

 // Add the value to the textarea:
 if ($value) echo $value;
 // Complete the textarea:
 echo '</textarea>';

 

Following is my php code -

 

echo '<form action="page.php" method="post">

<p><strong>Description:</strong></p>
<textarea name="description" rows="5" cols="45">' . $row[7] . '</textarea>
<div id="charCount"></div>
<script type="text/javascript">
function getCharCount(limit)
{
var tArea	    = document.getElementById("description"),
 countDisplay = document.getElementById("charCount");
 countRemains = limit - tArea.value.length
countDisplay.innerHTML = "Total characters : " + tArea.value.length + " Remaining: " + countRemains;
if (countRemains < 1) alert('Thats all folks');
}
</script>

<p><h2> Are you sure you want to delete your Notice?</h2></p>

<input type="radio" name="sure" value="Yes" /> Yes
<input type="radio" name="sure" value="No" checked="checked" /> No</br>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';
?>

 

Thanks

Link to comment
Share on other sites

Thanks,

 

I took out the single quotes and now the page comes up which is a good thing BUT the character limit is not working nor is the character count. The words can be entered forever. So this is the basic problem that I had when I started working on this area.

 

I don't really need the "That's All Folks" in there anyway and I tried several different ways of getting that out of there and was getting syntax errors.

 

Someone suggested above that I have too many inputs which is probably a problem. I have rearranged this but no change and the box stays the same size no matter what.

 

I know this has to be something stupid and something small but if I knew everything I wouldn't be posting to the forum. I am learning - comma by comma and semi-colon by semi-colon. Believe it or not.

 

Following is the forms_function.inc.php code –

 

} elseif ($type == 'textarea') { // Create a TEXTAREA.

 // Display the error first:
 if (array_key_exists($name, $errors)) echo ' <span class="error">' . $errors[$name] . '</span>';
 // Start creating the textarea:

 echo '<textarea name="description" id="description" rows="10" cols="54" value="<? =$row[7] ?>"onkeyup="getCharCount(50)"';

 // Add the error class, if applicable:
 if (array_key_exists($name, $errors)) {
  echo ' class="error">';
 } else {
  echo '>'; 
 }

 // Add the value to the textarea:
 if ($value) echo $value;
 // Complete the textarea:
 echo '</textarea>';

 

Following is the PHP code -

<p><strong>Description:</strong></p>
<textarea name="description" >' . $row[7] . '</textarea>
<div id="charCount"></div>
<script type="text/javascript">
function getCharCount(limit)
{
var tArea	    = document.getElementById("description"),
 countDisplay = document.getElementById("charCount");
 countRemains = limit - tArea.value.length
countDisplay.innerHTML = "Total characters : " + tArea.value.length + " Remaining: " + countRemains;
if (countRemains < 1) alert(Thats all folks);
}
</script>

<p><h2> Are you sure you want to delete your Notice?</h2></p>

<input type="radio" name="sure" value="Yes" /> Yes
<input type="radio" name="sure" value="No" checked="checked" /> No</br>
<p><input type="submit" name="submit" value="Submit" /></p>
<input type="hidden" name="id" value="' . $id . '" />
</form>';

Link to comment
Share on other sites

I think you should scrap the whole idea of a form function for creating the HTML. It just makes thing to complicated.

 

There two flaws in your code. First, your textarea has a name attribute, but no id. Inside the JS function, you try to get the element by ID, not by name. Secondly, the line with "countRemains" needs to be closed with a semi-colon. The function will not work because of that.

 

I would recommend you looking at a plugin for your browser called "firebug". It can spot JS errors for you, and you can debug JS values by using console.log() with variables. It will help you a lot. :)

  • Upvote 2
Link to comment
Share on other sites

Marie, I've noticed a bit of a theme in your most recent posts. The theme is essentially: I've got bugs in my code. Here's all my code. Fix it, please. Help!

 

This is not really what these forums are designed for. Please remember that we are all helping you for free, and we get nothing out of you getting your site to work. If possible, try to limit your topics to more conceptual topics or things related to specific code snippets, as opposed to asking us to debug your code.

 

Debugging is something that no one enjoys doing, but it's very important and something we all have to do. Larry also goes into a lot of detail in his books about how to debug and why being able to debug properly is important.

 

If you find yourself constantly running into bugs with no clue how to fix them, then you probably need to ask yourself if your fundamental approach is right to begin with. Specifically:

 

1) If you are trying to code something you are unfamiliar with (e.g., the character counter), expect failure. Over the years, as I have studied PHP and JS, there are many things that I have wanted to do, but have not been able to because my knowledge and experience at the time were too limited. It has only been years after the fact that I've finally been able to do some of those things that I wanted to do years before. As such, don't expect to always be able to do something new right away. Furthermore, your site should not depend on you having to do a bunch of things that you have no clue how to do. Ask yourself, "Do I really need a character counter that badly? Is it really worth the time investment?"

 

2) You really should code in pieces. Even now, I never write big swaths of code and then test it all at once. I will quite often write 2-3 lines of code at a time, and then test the code by echoing some value out to the screen to ensure I get what I want and that there are no syntax errors. This piecemeal approach will make debugging a lot easier.

 

3) Like Antonio said, don't overcomplicate your code for no reason. If you can do something a simpler way, do it the simpler way and/or note points 1) and 2) above.

 

I don't mean to sound overly critical, but I do tend to get annoyed by topics that are based around, "I have a bunch of code that doesn't work. Fix it!" I imagine you can understand that.

 

Anyway, I have no problem continuing this topic and helping you code a character counter, but let's avoid the "Please debug this" posts.

Thank you.

Link to comment
Share on other sites

Yes, you are absolutely right and was coming to the same conclusion myself.

 

However, in my defense I try only to ask for help when I think I have done everything myself to fix the situation including what debugging techniques I know and trying to relate my posts to code that is in the book. In this situation I didn't realize that this bit of code could only be done in Javascript and of course the book doesn't cover Javascript.

 

And you are right. I have been asking myself, "Do I really need a character counter or whatever, that badly?" but thought that I WAS coding in pieces and a most of the time comparing code to other bits of codes that were simliar from the book or code that I have used before that works, so therefore, "why doesn't this code work?"

 

Didn't realize that I may be coming across as asking people to debug my code, but if anyone is posting anything about coding then they must be in a situation where their code needs debugging. So you are saying the forums are not about codes that don't work. So that is fine, I understand.

 

I am not going to pursue the character counter in this case. I will do it later if I find any users complaining. I did discover some interesting things after reading Antonio's post above.

 

Thanks for all your help. With my limited experience I have also tried to help where I can.

 

Marie

Link to comment
Share on other sites

Didn't realize that I may be coming across as asking people to debug my code, but if anyone is posting anything about coding then they must be in a situation where their code needs debugging. So you are saying the forums are not about codes that don't work. So that is fine, I understand.

 

I don't know what HartleySan was trying to say, but as the only moderator of these forums, I can plainly tell you that these forums ARE for help with code that doesn't work. But the forums are also for people with general approach questions, interest in sharing what they've learned, specific bits of help, etc.

 

In my mind, what I want to see is that the poster isn't being lazy; that they've done some work. If a person repeatedly posts messages that are similar in nature, or have not gone through the proper steps themselves, that's discouraging. And if a person just repeatedly needs basic debugging help, that's not really a good use of anyone's time, except for helping the person learn how to debug. So there's a balance there. But the forums are definitely for people who need help with their code.

 

The forums are for helping and learning, in whatever forms that may be.

Link to comment
Share on other sites

I definitely have been learning from these forums - not just with the responses to my posts but I frequently go through other people's posts. You wouldn't believe how far I have come since starting my own site.

 

When I started, I was working in Dreamweaver only which does have a character counter that works very well and is very simple. However, I soon learned that Dreamweaver couldn't do all that much and I found other sources, including your books and books and forums by others.

 

Still it can get confusing and it appears like some PHP codes works in some situations and not in others. So that has been a bit of a struggle for me. Why does it work on one page and then I try to integrate it into a similar situation on another page and it just doesn't work.

 

My site is almost finished and I will be revisiting the PayPal thing which wasn't quite working for me either. Anyway, maybe when I am done and actually bring in some money I can afford to hire some people to keep it up for me.

 

Marie

Link to comment
Share on other sites

Marie, thank you responding to my previous (somewhat scathing) post. Looking back, I realize that I was a bit presumptuous in my assessment, especially considering the fact that I of course don't know your entire situation and have no way of knowing what kind of effort you're making before you make a post.

 

Between your previous thread (which margaux and I responded to) and this thread, I just got the feeling that you were "going to the well too many times", per se, and it just seemed like for many posts in a row, you were posting big blocks of code and saying, "Here, fix this."

 

Like Larry said though, there is no rule against this, but in my (limited) view, I felt like you weren't making enough effort as (again, in my view) the syntax errors and whatnot that you were experiencing were fairly simply to fix if you followed the instruction that margaux and I provided in your previous thread, and the advice we have provided for you in this thread.

 

Knowing what I know now though, you obviously would not have asked the questions if you knew the answer, so I apologize for snapping at you. I hope I didn't scare you away. I like trying to help you (I just wish there were fewer, "I have a bug I can't fix" posts). But then again, those posts are sometimes inevitable; Larry certainly knows that I've asked my fair share.

 

To end this post, I am sorry for being overly presumptuous and getting annoyed at what you were posting without all the facts, and I hope I didn't scare you away or perhaps make you not what to post legitimate questions you may have in the future (even if they involve debugging code).

Link to comment
Share on other sites

Good guy Jon here. Nice gesture. :)

 

Marie: Get a nice IDE. It will help you a lot. Those syntax errors will be highlighted and easy to spot. I can recommend Eclipse or Netbeans. Besides having "Projects", an IDE is really only a powerful text editor specialized for coding. A project is simply something used to organize your code with. Create a new "Marie's website" project, move your files into the folder created, and you are ready to go. Both are free. You should figure it out quickly, and never look back.

 

The benefits are so great that you should switch instantly. Don't remember a function name? Start typing, and it will suggest for you. Don't remember variable names? Ide will keep track. Errors in code? IDE will tell.

 

Download Eclipse here (Download links to the right)

Link to comment
Share on other sites

HartleySan - Thank you for your comments. I WAS scared a little bit but can usually bounce back fairly quickly. Usually I don't post until I am tearing my hair out and I think by that time that it is something small that I am not seeing myself. I also usually try all the suggestions that people make but if I don't directly get back to someone - either on this forum or another it is because it didn't work for me. So then I sometime leave it for a few days to look at things again with fresh eyes, however, I know that other people may be looking for a response and be frustrated at trying to help but the person (me) is not getting back to the post.

 

I will revisit the debugging techniques. For the most part I am working live, not on a local host. I have my test site nested inside another live URL so there are a few different things that can happen there.

 

Antonio - I will check out Eclipse. I have tried Netbeans before and didn't like it all that much. As an IDE Dreamweaver doesn't bother me all that much and I also have TextWrangler.

 

Thanks to everyone for their help.

 

Marie

Link to comment
Share on other sites

Marie, I had some spare time, so I decided to write up a quick JS solution for adding a character counter to a text area.

 

Please take a look at the following code (explained below):

 

<!DOCTYPE html>

<html lang="en">

 <head>

   <meta charset="UTF-8">

   <title>Text area character counter</title>

   <style>

     textarea {

       height: 200px;

       width: 40%;

     }

   </style>

 </head>

 <body>

   <textarea id="the_textarea" maxlength="50"></textarea>

   <p>Remaining characters: <span id="remaining_chars"></span></p>

   <script>

     function setCharCounter(input_elem_str, remaining_chars_elem_str, char_limit) {

       var elem = document.getElementById(input_elem_str),
         remaining_chars_elem = document.getElementById(remaining_chars_elem_str);

       remaining_chars_elem.innerHTML = char_limit;

       elem.onkeydown = function () {

         truncate(this, remaining_chars_elem, char_limit);

       };

       elem.onkeyup = function () {

         truncate(this, remaining_chars_elem, char_limit);

       };

     }

     function truncate(elem, remaining_chars_elem, char_limit) {

       if ((elem.value.length - char_limit) > 0) {

         elem.value = elem.value.substr(0, char_limit);

       }

       remaining_chars_elem.innerHTML = char_limit - elem.value.length;

     }

     setCharCounter('the_textarea', 'remaining_chars', 50);

   </script>

 </body>

</html>

 

By adding the setCharCounter and truncate functions to your code, you can attach a character counter to any text area (or text input box) by simply calling the setCharCounter function with the three required arguments.

 

The first argument is the ID of the text area to attach the counter to, the second argument is the ID of the element to place the remaining character counter in, and the third argument is the max limit on the number of characters.

 

With the setCharCounter and truncate functions, I do a few things:

 

- First, I get DOM references to the text area element and the span element within the p element, and assign those references to variables. By the way, a span element within a p element is probably the most semantically sound way to handle a remaining character counter.

 

- Right after the variable declarations, I set the number of remaining characters to the character limit (since I'm assuming that nothing has been entered into the text area yet).

 

- I set up both onkeydown and onkeyup event handlers for the text area. As I noted in a previous post, this seems to be the best way to avoid all sorts of weird behavior that can result if you use only the onkeydown event handler or only the onkeyup event handler.

 

- Within the anonymous function called by each of the event handlers, I called the truncate function. Truth be told, I didn't need to write this function in the first place; I could have just placed the code in the truncate function within the anonymous function definitions, but I decided to do this to avoid repetitive code and make the code easier to edit, if necessary.

 

- Lastly, within the truncate function, I check if the max character limit has been exceeded and if so, truncate the string, and then calculate the number of remaining characters and output that to the screen.

 

Please also note that I added the maxlength attribute to the text area. This is the best solution for HTML5 browsers that support it. Also, you should still check the string length on the PHP side just to be safe (after all, the user may have JS disabled, rendering all of the above useless).

 

Is that of any use to you (or have you already found a better solution elsewhere)?

Link to comment
Share on other sites

I am sure that this will be of use to me. Thank you for spending your spare time posting this code.

 

I have gone through it but will have to get back to the forum in a few days. I went on to another area of my site and left this for the time being. As you mentioned before, having a character count isn't critical. It seems that most sites have them though.

 

I have found that MOST codes provided work well on their own in their own page as does this one. I seem to have problems when trying to integrate JS into any of my PHP pages.

 

Thanks again.

Link to comment
Share on other sites

Well, good luck with everything.

Like I said before, the only thing that would cause a problem when you integrate the code is a namespace conflict in JS (i.e., you already have other functions of the same name on the same level), or syntax errors in your code.

 

Other than that, there shouldn't be any issues, especially with the character counters on the Internet, which are likely more modularized than my example above, which is more designed for teaching purposes so you can code your own, if need be.

Link to comment
Share on other sites

 Share

×
×
  • Create New...