Method 1: jQuery
Seeing as you have jQuery tagged, I'm going to give you a jQuery solution:
$(function() {
// Define our maximum length
var maxLength = 50;
// Our input event handler, which fires when the input changes
$('textarea.scanwid').on('input', function() {
// Pull the input text and its length
var value = this.value,
length = value.length;
// Check if the length is greater than the maximum
if (length > maxLength) {
// If it is, strip everything after the maximum amount
this.value = this.value.substring(0, maxLength);
// Ensure our counter value displays 0 rather than -1
length = maxLength;
}
// Update our counter value
$('input[name="q22length"]').val(maxLength - length);
});
});
Method 2: HTML and jQuery
It's also worth noting that we could just stick the maxlength
attribute onto our textarea
element:
<textarea ... maxlength="50"></textarea>
We can then update our counter using this:
$(function() {
var maxLength = +$('textarea.scanwid').attr('maxlength');
$('textarea.scanwid').on('input', function() {
$('input[name="q22length"]').val(maxLength - this.value.length);
});
});