Created
January 11, 2013 21:29
-
-
Save toddaeverett/4514107 to your computer and use it in GitHub Desktop.
Character limiter for textarea boxes. Keeps character count from going over a set limit, even if pasting text in. Might need jquery to work. Not sure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script language="JavaScript"> | |
function limiter( event, field, limit ) { | |
backspace = 8; | |
del = 46; | |
tab = 9; | |
if( !event ) event = window.event; | |
key = ( event.which ? event.which : event.keyCode ); | |
//display_field.innerHTML += String.fromCharCode(key); | |
field_text = field.value; | |
if( field_text.length >= limit && key != backspace && key != del && key != tab && !( key >= 37 && key <= 40 ) ) { | |
trim_text( field, limit ); | |
return false; | |
} | |
} | |
function trim_text( field, limit ) { | |
field_text = field.value; | |
if( field_text.length > limit ) { | |
field_text = field_text.substr( 0, limit ); | |
field.value = field_text; | |
} | |
} | |
function update_limit_display( field, limit, display ) { | |
display_field = document.getElementById( display ); | |
field_text = field.value; | |
if( field_text.length == 0 ) display_field.innerHTML = limit + " character(s) remaining."; | |
else if( field_text.length >= limit ) display_field.innerHTML = "0 character(s) remaining."; | |
else display_field.innerHTML = ( limit - field_text.length ) + " character(s) remaining."; | |
} | |
</script> | |
<p><label for="dietRestrictions">List any restrictions regarding food and diet.</label><br /> | |
<textarea name="dietRestrictions" rows="5" style="width:575px;" onkeypress="return limiter( event, this, 1000 );" onkeyup="trim_text( this, 1000 ); update_limit_display( this, 1000, 'limit_dietRestrictions' );" onchange="trim_text( this, 1000 );"></textarea><br /> | |
<span id="limit_dietRestrictions">1000 character(s) remaining.</span></p> | |
<p><label for="allergies">Specify any health problems, allergies or disabilities.</label><br /> | |
<textarea name="allergies" rows="5" style="width:575px;" onkeypress="return limiter( event, this, 1000 );" onkeyup="trim_text( this, 1000 ); update_limit_display( this, 1000, 'limit_allergies' );" onchange="trim_text( this, 1000 );"></textarea><br /> | |
<span id="limit_allergies">1000 character(s) remaining.</span></p> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment