Page 1 of 1

Limit characters in a textfield

Posted: Mon May 10, 2010 10:02 am
by klevis miho
How can I limit the number of characters used in a textfield?

Re: Limit characters in a textfield

Posted: Mon May 10, 2010 10:13 am
by dimxasnewfrozen
I use something like:

Code: Select all

<script language="javascript">
function CountLeft(max) {
	 field = document.getElementById("message");
	 count = document.getElementById("left");
	 if (field.value.length > max)
		field.value = field.value.substring(0, max);
	 else
	// calculate the remaining characters  
	 count.value = max - field.value.length;
}
</script>
<input readonly type="text" name="left" id="left" size=3 maxlength=3 value="100"> <font size="-1">Chars Remain (100 Max). </font>
<textarea id="message" name="message" style="width:100%; height:100px;" onKeyDown="CountLeft(100);" onKeyUp="CountLeft(100);"></textarea>


Re: Limit characters in a textfield

Posted: Mon May 10, 2010 10:16 am
by klevis miho
Thnx man, but if the user turns JS off?

Re: Limit characters in a textfield

Posted: Mon May 10, 2010 10:26 am
by dimxasnewfrozen
Well if it's a simple text box you can use the html maxlength property :

<input type="text" maxlength=50 name="mytextbox" />

I don't believe the textarea box has a maxlength property, you may need to use javascript or you can validate the textarea length with php after it has been submitted.

Code: Select all

$text = $_POST['mytextarea'];
if (strlen($text ) > 10) {
	echo "You entered to many characters!";
	exit;
}

Re: Limit characters in a textfield

Posted: Mon May 10, 2010 10:38 am
by klevis miho
Thnx dimxasnewfrozen, but the reason I wanted this is to avoid strlen function to count a big number of characters, so the server will be more faster