Created
June 12, 2014 19:50
-
-
Save robertcdawson/697a3810ae455285d0b2 to your computer and use it in GitHub Desktop.
Add a character count below any input field
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
function setCount(source, target, limit) | |
{ | |
var chars = source.val().length; | |
if (chars > limit) | |
{ | |
// Disable submit button | |
jQuery("input#submit").attr('disabled', 'disabled'); | |
source.css("background", "#fee"); | |
target.css("color", "red"); | |
if ((chars - limit) > 1) | |
{ | |
target.text((chars - limit) + " characters over the limit"); | |
} | |
else | |
{ | |
target.text((chars - limit) + " character over the limit"); | |
} | |
} | |
else | |
{ | |
// Enable submit button | |
jQuery("input#submit").removeAttr('disabled'); | |
source.css("background", "white"); | |
target.css("color", "green"); | |
target.text(chars + " chars (" + (limit - chars) + " left)"); | |
} | |
} | |
jQuery("#my_source").after(" <span id='my_source_count'></span>"); | |
jQuery("#my_source").on("keyup focus", function() | |
{ | |
setCount(jQuery(this), jQuery("#my_source_count"), 600); | |
}); | |
setCount(jQuery("#my_source"), jQuery("#my_source_count"), 600); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment