Last updated on November 26th, 2024 at 12:31 pm
Find the JavaScript code snippet intended to limit the number of characters that can be entered into a text field within a form,
The script will look like this
<script language="javascript">
var count = 125; // Character limit
function limiter() {
var commentBox = document.forms["myform"]["comment"];
var limitDisplay = document.forms["myform"]["limit"];
var len = commentBox.value.length;
if (len > count) {
commentBox.value = commentBox.value.substring(0, count);
limitDisplay.value = "Limit reached";
} else {
limitDisplay.value = "Characters remaining: " + (count - len);
}
}
</script>
We do have a HTML form where we have the textarea displayed.
<form name="myform">
<textarea name="comment" onkeyup="limiter();" rows="4" cols="50"></textarea><br>
<input type="text" name="limit" readonly>
</form>
The limiter
function:
- Tracks the length of the input in the
textarea
. - Updates the
limit
input field to display how many characters remain. - Truncates the input if it exceeds the limit.
User-friendly messages:
"Characters remaining: X"
when within the limit."Limit reached"
when the character limit is exceeded.