#1
  1. No Profile Picture
    Gone PHP Crazy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Location
    Melbourne, Australia
    Posts
    393
    Rep Power
    12

    Re-using Javascript


    I have the following javascript to restrict the user input to certain number of characters in a textarea field
    Code:
    function calcChars(f, lengthoftextarea) 
    {
      var maximum = lengthoftextarea;
      var i = maximum - f.description.value.length;
      if (i < 0) {
        f.description.value = f.description.value.substring(0, maximum);
        alert("You have reached the maximum length of your message.");
        f.charMessage.value = 0;
        return false;
      }
      f.charMessage.value = i;
      return true;
    }
    The html for using the function is like this:
    Code:
    characters: <input readonly type="text" name="charMessage" size="3" value="255" style="border:0px; background:transparent; width:30px"><br />
    <textarea cols="40" rows="8" name="description" id="description" onKeyUp="calcChars(this.form, 255);" ></textarea>
    I want to re-use the above javascript so that I can use it for multiple textarea objects on the same form and each textarea showing different character limits. I don't want to duplicate the function for each textarea. I think the key is to pass the right object to the function. Someone please show me how to ?
    visit http://www.techsatcomputers.com
  2. #2
  3. mod_dev_shed
    Devshed Supreme Being (6500+ posts)

    Join Date
    Sep 2002
    Location
    Atlanta, GA
    Posts
    14,817
    Rep Power
    1100
    Code:
    function calcChars(ta, ro, max)
      {
      // ta = textarea
      // ro = readonly field
      // max = maximum characters allowed
      var diff = max - ta.value.length;
      if(diff < 0)
        {
        ta.value = ta.value.substring(0, max);
        alert('You have reached the maximum length of your message.');
        ro.value = 0;
        return false;
        }
      ro.value = diff;
      return true;
      }
    Code:
    Characters: <input type="text" name="chars" value="255"><br>
      <textarea cols="40" rows="8" name="description" onkeyup="calcChars(this,this.form.chars,255);"></textarea>
  4. #3
  5. No Profile Picture
    Gone PHP Crazy
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2003
    Location
    Melbourne, Australia
    Posts
    393
    Rep Power
    12
    Thanks that worked as expected

IMN logo majestic logo threadwatch logo seochat tools logo