Created
August 22, 2012 17:05
-
-
Save mckellip/3427574 to your computer and use it in GitHub Desktop.
Add max length and character counter to html text areas using jquery
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
/* HTML Needed | |
* <textarea id="area1" maxlength="250"></textarea> | |
* <span class="area1"></span> | |
*/ | |
$('textarea[maxlength]').on('focus keyup', function (e) { | |
var ml = this.getAttribute('maxlength'); | |
var c = $('.' + this.id); | |
var tv = this.value; | |
var l = tv.length; | |
if (e.type === 'focus') { | |
c.append('(<span class="charLeft"></span> characters left of <span class="charTotal"></span>)'); | |
c.children('.charLeft').text(ml - l); | |
c.children('.charTotal').text(ml); | |
$(this).off('focus'); | |
} else { | |
var v = 0; | |
(l >= ml) ? $(this).val(tv.substring(0, ml)) : v = ml - l; | |
c.children('.charLeft').text(v); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment