An ignorant American asks...

Hi,

My name is Bill Dale, I live approximately 200 miles south of Canada, in Minnesota (USA, where the forecast high temperature this coming Friday is 15 degrees BELOW ZERO Fahrenheit - imagine that!), and while I don't want to be pest, I find myself buffaloed by the question of, "How in the world can a person use your - wonderful - character count javascript for five different fields on the same page?

I'm referring to your script (which really IS nice) at:

http://sarahk.pcpropertymanager.com/muck/chars.php

I'm working on an employment application that has five "comment" entry fields in it (previous experience, educational description, etc.), that have a 255 char limit and would love to use it in each instance. Unfortunately, you could fit my knowledge of javascript in a miniature thimble. Let's see if I can give you a clear and concise picture of what I mean:

  1. I SEEM to be aware of the general fact that it is impossible to run the same script on the same page because of the variables and function names "not cooperating" (with the use instance number two, three, etc.); and that
  2. That problem CAN be gotten around by changing the names of those things slightly in each instance; but
  3. My ignorance of javascript is so thorough that I am unable to discern all the function and variable names in your script (or how to make sure the onkeyup="keyup(this)"> and <div id="txtmsg"> get changed properly to match those changes in the script).

A person wouldn't think it would be that difficult to examine and figure out (I have managed to do it a time or two with other, seemingly more complicated scripts - much longer, anyway), but I've reached that point where I'm simply going crazy: The first time I tried to doctor things, nothing would work. I have managed to get things to the point where at least the first "comment" field counter works, but not the second, etc. (nothing happens).

And, believe me, I wouldn't bother you with this if I hadn't scoured the net for answers. Unfortunately, even though I'd think it would be, the question of using the same script multiple times on the same web page doesn't seem to be a hot topic. And whatever info I have been able to unearth keeps point back to changing the variable and function names which has me trapped in the fog loop.

Code Reusability

Now, this page is all about the functionality to restrict the amount of text a user can enter into a text box. Useful for any number of applications. But what this is really showing is how one piece of code (comprising 3 functions) can be used over and over on a page. This is acheived through careful coding and ensuring that the right information is passed to allow the function to know what it is doing.

One of the big problems I have with Dreamweaver sites is that it bundles a huge bunch of javascript onto the page. The code is good, complex and fits a wide variety of circumstances. The downside is that in it's flexibility it often requires a large number of variables to be passed making the code quite cumbersome. There is a constant trade off between:

  • the need to be able to customise code for your own circumstance versus "plug and play" scripts
  • hardcoded, single purpose scripts and flexible multi purpose scripts.

Finding the balance will depend on your skills, the time you have available and your motivation.

A Kiwi replies...

Sorry Bill but you shouldn't give antipodeans such good ammo :)

Anyway, I staggered off the beach, shook off the sand, booted up my PC and took pity on anyone who has winters which are 15 below anything.

Anyway, the crux of the issue is "reusability" of code and is the mainstay of languages such as Java, C++ and other OO languages. As you've worked out you need to be able to tell the script just which version is using the script at any given time. The LAST thing we'd want to do is create 5 versions of the script.

My Example

I've reworked by Text Area Char Count script to have 2 text areas to manage, could just as easily be 5 but I've just done 2.

I've added a new function to manage the grab of the text in the boxes and this has to be done right to ensure that it works across the browsers. I'm no expert there so google for "javascript browser compliance" and you'll find a stack of information.

In the original example I passed "this" which was the actual field and then updated a hardcoded div with the count. Not terribly smart but functional. As Bill has pointed out hard coding can be hard to fix if you're not particularly strong on javascript.

So, instead each text area passes in it's own name and the name of the corresponding feedback div. These could be anything - and aren't restricted any particular format. View the source and see how it works, add some alerts so you can see what is passed from place to place. The code is relatively simple.

Functions:

  • countChars - controls the logic and business rules (as such)
  • txtshow - simple function to display a given string on the page
  • getTxt - simple function to retrieve a string from the page

And don't forget, move it to a separate file so the javascript is cached away from your page.


Enter Text into the boxes below.

 
 
 
All the work is done by javascript, so just view the source to see how it's done.

Disclaimer: I'm no javascript guru

However if you need an explanation here's my take on it...

var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};

These lines create 2 global variables which are available to any javascript function. They identify the type of browser you have to ensure compliance.

function txtShow( cId, txt2show )
{
   // Detect Browser
   if (DOM) {
      var viewer = document.getElementById(cId);
      viewer.innerHTML=txt2show;
   }
   else if(IE) {
      document.all[cId].innerHTML=txt2show;
   }
}//txtshow

txtShow displays the message in the appropriate div. innerHTML is not without it's challenges but this use of it is simple and straight forward. It uses the global variables to detect the appropriate method for displaying the string. The function has two arguments:

  1. cId is the name of the div; and
  2. txt2show is the string which will be displayed.
function getTxt( cId )
{
   var output = "";
   // Detect Browser
   if (DOM) {
      var viewer = document.getElementById(cId);
      output = viewer.value;
   }
   else if(IE) {
      output = document.all[cId].value;
   }
   return output;
}//getTxt

getTxt controls the retrieval of the string from the text area. A variable cId is passed but the value is the name of the text area. The function has 1 argument

  1. cId is the name of the textarea
function countChars(cBoxName, cTxtName, maxKeys)
{
   var str = new String(getTxt(cBoxName));
   var len = str.length;
   var showstr = len + " characters of " + maxKeys + " entered";
   if (len > maxKeys) showstr += '<br>Some information will be lost, please revise your entry';
   txtShow( cTxtName, showstr );
}

Unlike keyup in the previous example countChars receives three string arguments

  1. cBoxName: the name of the textarea that the user is typing into
  2. cTxtName: the name of the div to put the count message into
  3. maxKeys: the maximum number of characters accepted in this particular textarea

This script gets the textarea contents and then gets the length of it. We force the content to be a string object, just in case it's null. We can use the string's length method to get the length. Using the length we can then make our basic feedback message and check to see if we need the warning. txtShow is then called to display the message. We could just as easily have called txtShow with the textarea name and a truncated string to fit out maximum length ... or something else altogether.

Because these scripts have been hacked a bit the naming conventions aren't enforced strongly.

 

© 2000 - Estatement Ltd