Created
August 2, 2013 19:34
-
-
Save dev1ne/6142749 to your computer and use it in GitHub Desktop.
Limit characters in textarea (with maxlength attribute fallback)
This file contains hidden or 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
| //Limit max characters in textarea | |
| $(".textarea-limit").each(function () { | |
| var thistextarea = $(this); | |
| var characters = thistextarea.prop('maxlength'); | |
| thistextarea.prev('label').append("<span class='limit-counter'>You have <strong>"+ characters+"</strong> characters remaining</span>"); | |
| var counter = thistextarea.prev('label').find('.limit-counter'); | |
| counter.css('float','right'); | |
| function displaycounter(countervar) { | |
| var remaining = characters - countervar.val().length; | |
| counter.html("You have <strong>"+ remaining+"</strong> characters remaining"); | |
| if(remaining <= 10) { | |
| counter.css("color","red"); | |
| } | |
| else { | |
| counter.css("color","black"); | |
| } | |
| } | |
| displaycounter(thistextarea); | |
| thistextarea.keyup(function(){ | |
| if (!$.support.maxlength) { | |
| if ($(this).val().length > characters) { | |
| $(this).val($(this).val().substr(0, characters)); | |
| } | |
| } | |
| displaycounter($(this)); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment