Limit characters in a textfield
Moderator: General Moderators
-
klevis miho
- Forum Contributor
- Posts: 413
- Joined: Wed Oct 29, 2008 2:59 pm
- Location: Albania
- Contact:
Limit characters in a textfield
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
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
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
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.
<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
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