Forum Moderators: coopster

Message Too Old, No Replies

PHP & Javascript To Limit <textarea> Characters

Can it be written like this?

         

soquinn

5:29 am on Mar 2, 2004 (gmt 0)

10+ Year Member



Hello, not sure if javascript can go with PHP like this... any suggestions on how or if this can be done to limit the number of characters in a <textarea>?

$this->body .="<td><textarea name=description cols=30 rows=10 onkeypress="textCounter(this,this.form.counter,430)";>".urldecode($class_ad->DESCRIPTION)."</textarea>\n";

$this->body .="<input type=text name=counter maxlength=3 size=3 value=430 onblur="textCounter(this.form.counter,this,255);">Characters remaining if neded.</td></tr>\n";

coopster

1:25 pm on Mar 2, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Yes, you can write javascript in your PHP code just as you would HTML. However, it needs to be escaped correctly:
$this->body .="<td><textarea name=description cols=30 rows=10 
onkeypress=\"textCounter(this,this.form.counter,430)\";>"
.urldecode($class_ad->DESCRIPTION)."</textarea>\n";

As far as limiting the number of characters in a textarea, you can use javascript on the client-side, but you may want to verify the length again on the server-side with PHP in case your form was tampered:
$description = (isset($_POST['description])) ? $_POST['description] : ''; 
$descMax = 255;
if (strlen($description) > $descMax) {
// handle the tampered description field issue
}

soquinn

5:39 pm on Mar 2, 2004 (gmt 0)

10+ Year Member



Thanks coopster, works great. Is there an easy way within that code to say the field is also a required field?

coopster

6:23 pm on Mar 2, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Client-side? You could use javascript to check for a value in that particular form element and display a message accordingly.

Server-side? You will want to do this anyway, since client-side entries can be manipulated and bypassed. Especially consider if they have javascript turned off in their browser! To check server-side, just see if there is anything in the $_POSTed variable:

$description = (isset($_POST['description]))? $_POST['description] : '';  
if (!$description) {
// handle the error
}

$descMax = 255;
if (strlen($description) > $descMax) {
// handle the tampered description field issue
}