Simple textarea text counter using bootstrap | 2my4edge

06 May 2015

Simple textarea text counter using bootstrap

Twitter style textarea character counter using Bootstrap and javascript, here is the one of the simple method use the textarea counter, this is very useful to limited character field in forms. after a long time this post is about bootstrap. It is very simple one. text counter with validation until you fill textarea field.  lets see the code. 

Simple text counter with bootstrap
DOWNLOAD                LIVE DEMO

BOOTSTRAP FILES CSS AND JS
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.0/
            css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<style type="text/css"> 
    .red{ color:red;}
    textarea { resize:none; }
</style>
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.3.0/
            js/bootstrap.min.js"></script>

HTML CODE
<form action="" method="post" >
    <div class="form-group col-md-6">                                
        <label id="messageLabel" for="message">You Text content </label>
        <textarea class="form-control input-sm" type="textarea" id="message" 
            placeholder="Text goes here" maxlength="150" rows="8"></textarea>
        <span class="help-block">
            <p id="characterLeft" class="help-block ">You have reached the limit</p>
        </span>                
    </div>
    <br style="clear:both">
    <div class="form-group col-md-2">
        <button class="form-control input-sm btn btn-success disabled" id="btnSubmit" 
        name="btnSubmit" type="submit" style="height:35px"> Send </button>    
    </div>
</form>
Here we are giving maxlength in textarea to avoid more that maxlength charecter, the script is the instant count of the text in textarea.

JAVASCRIPT
<script type="text/javascript">
$(document).ready(function(){ 
$('#characterLeft').text('150 characters left');
$('#message').keydown(function () {
var max = 150;
var len = $(this).val().length;
if (len >= max) {
    $('#characterLeft').text('You have reached the limit');
    $('#characterLeft').addClass('red');
    $('#btnSubmit').addClass('disabled');            
} 
else {
    var ch = max - len;
    $('#characterLeft').text(ch + ' characters left');
    $('#btnSubmit').removeClass('disabled');
    $('#characterLeft').removeClass('red');            
}
});    
});
</script>

i hope this post is really helpful to you, thanks for visiting, keep in touch with us for more updates in web design and development, Thank you.




No comments:

Post a Comment

^