Limit characters in a textfield

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Limit characters in a textfield

Post by klevis miho »

How can I limit the number of characters used in a textfield?
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Re: Limit characters in a textfield

Post 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>

klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Limit characters in a textfield

Post by klevis miho »

Thnx man, but if the user turns JS off?
dimxasnewfrozen
Forum Commoner
Posts: 84
Joined: Fri Oct 30, 2009 1:21 pm

Re: Limit characters in a textfield

Post 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;
}
klevis miho
Forum Contributor
Posts: 413
Joined: Wed Oct 29, 2008 2:59 pm
Location: Albania
Contact:

Re: Limit characters in a textfield

Post 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
Post Reply