jquery - Reducing count value in span based on number of characters entered in textarea -


i have been trying implement character counter displays number of chars user can enter inside text area using jquery. here code:

html:

<textarea id="questiontextbox"  placeholder="enter question e.g. how pay raise?" name="data[qna_question][question_text]"></textarea>  <span id="noofchar">128</span> characters remaining 

jquery:

jquery(document).ready(function(){   jquery("#questiontextbox").keypress(function () {     var qtext = jquery("#questiontextbox").val();     if(qtext.length <= 127) {     jquery("#noofchar").html(128 - qtext.length - 1);    } else {        jquery("#questiontextbox").val(qtext.substring(0,128));    }    }); 

});

here jsfiddle http://jsfiddle.net/cy667/

it's not working correctly.

  1. when reaches 128 character should not take more values
  2. when delete characters, counter should increase. not increasing when delete first few characters after reaching 128 limit.

you need use 3 jquery key events catch user keyboard.

this should fix problems: jsfiddle

$(document).ready(function(){      function updatecount ()     {         var qtext = jquery("#questiontextbox").val();         if(qtext.length < 128) {            jquery("#noofchar").html(128 - qtext.length);        } else {            jquery("#noofchar").html(0);            jquery("#questiontextbox").val(qtext.substring(0,128));        }     }      $("#questiontextbox").keyup(function () {         updatecount();     });     $("#questiontextbox").keypress(function () {         updatecount();     });     $("#questiontextbox").keydown(function () {         updatecount();     }); }); 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -