1

I found a script for limiting the number of characters input in a textarea. It generally works well.

    <script language="javascript" type="text/javascript">
     function limitText(limitField, limitCount, limitNum) {
        if (limitField.value.length > limitNum) {
    limitField.value = limitField.value.substring(0, limitNum);
        } else {
    limitCount.value = limitNum - limitField.value.length;
     }
     }
  </script>

It is called in the following way:

    onKeyDown="limitText(this.form.areaname,this.form.countdown,150);"
    onKeyUp="limitText(this.form.areaname,this.form.countdown,150);"

On one particular page there can be multiple text areas generated by a repeat loop that are named as

    textarea<?php echo $i; ?>

where $i increments each time.

I have tried various things such as

    $areaname = "areaname" . $i;

and then

    onKeyDown="limitText(this.form.'<?php echo $areaname; ?>',

but cannot get anything to work.

Some help would be much appreciated

  • 1
    What is the error message or what went wrong? – ToBe Jan 30 '14 at 16:33
  • Can you use the `maxlength` attribute? – tymeJV Jan 30 '14 at 16:34
  • 1
    `this.form.'foo'` is illegal javascript anyways. `this.form.foo` or `this.form['foo']` would work. Remember that even though you're working with PHP, you have to generate VALID **javascript**. – Marc B Jan 30 '14 at 16:36
  • That function won't work properly on all browsers. Firefox and (I think) Chrome/Safari report an incorrect length for textarea elements with hard newlines (newlines present due to the user hitting "Enter".) – Pointy Jan 30 '14 at 16:36
  • @tymeJV I don't think `maxlength` works properly in Firefox or WebKit. – Pointy Jan 30 '14 at 16:37

0 Answers0