Wednesday, 8 October 2014

Live Character Counter using jQuery



<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var maxCharAllowed = 140; // Maximum number of characters allowed
$("#display").append("You are left with <b>"+ maxCharAllowed+"</b> characters");
$("#text").keyup(function(){
if($(this).val().length > maxCharAllowed){ // Compare if still user can enter more characters
$(this).val($(this).val().substr(0, maxCharAllowed)); // dont let user enter more than allowed number of characters
}
var leftCharacters = maxCharAllowed - $(this).val().length;
$("#display").html("You are left with <b>"+ leftCharacters+"</b> characters");
if(leftCharacters <= 10)
{
$("span").addClass("warning");
}
else
{
$("span").removeClass("warning");
}
});
});

</script>
<div id="demo">
<form style="width:500px;" id="myform" method="POST" action="#">
<textarea id="text"></textarea>
<br/>
<input type="submit" value="Submit">
</form>
<span id="display"></span>
</div>

0 comments:

Post a Comment