Learn free online HTML5, javascript, and jquery Tutorials by Examples

Monday 26 May 2014

Textarea Character Limit with jQuery

---------------------------------------------------
<script src="http://http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script>
      $(document).ready(function(){
  var limitnum = 120; // set your int limit for max number of characters
 
  function limiting(obj, limit) {
    var cnt = $("#counter > span");
    var txt = $(obj).val();
    var len = txt.length;
   
    // check if the current length is over the limit
    if(len > limit){
       $(obj).val(txt.substr(0,limit));
       $(cnt).html(len-1);
     }
     else {
       $(cnt).html(len);
     }
   
     // check if user has less than 20 chars left
     if(limit-len <= 20) {
      $(cnt).addClass("warning");
     }
  }


  $('textarea').keyup(function(){
    limiting($(this), limitnum);
  });
});
</script>

<style>
     #w { max-width: 850px; min-width: 350px; box-sizing: border-box; padding: 15px 10px; margin: 0 auto; background: #fff; box-shadow: 1px 1px 2px rgba(0,0,0,0.35); border-radius: 4px; -moz-border-radius: 4px; -webkit-border-radius: 4px; }

#counter { font-size: 1.3em; color: #7e7e7e; margin-bottom: 9px; }
#counter span { font-style: italic; font-size: 2.1em; line-height: 1.55em; color: #a99bb1; }

#counter span.warning { color: #b66875; }

.txt { outline: none; width: 65%; height: 130px; padding: 9px 16px; font-size: 1.5em; line-height: 1.35em; color: #454545; border-top: 1px solid #c1c1c1; border-left: 1px solid #b7b7b7; border-bottom: 1px solid #818181; border-right: 1px solid #818181; box-shadow: 0px 1px 1px rgba(0,0,0,0.35); }
</style>


<div id="w">
  <h1>Live Textarea Count Limit</h1>
  <h3 class="desc">Text is limited up to 120 characters</h3>
 
  <p id="counter"><span>0</span> characters</p>
 
  <textarea name="text" id="text" class="txt" tabindex="1"></textarea>
  </div>


---------------------------------------------------

No comments:

Post a Comment