PoliDev
PoliDev

Reputation: 1458

Limit/Count number of chracters in TextArea using jquery

How to count the characters what entered in text area box?

I have textbox like the following,

 <%: Html.TextArea("Message", "", new { @title = "Enter the Message" })%>

My maximum count is 160 characters. If the characters gettng exceeds it should show the count of the characters / 2 messages. How to count the charaters ?

Upvotes: 2

Views: 342

Answers (2)

chridam
chridam

Reputation: 103365

You could try adding a jquery event handling method:

Markup:

<%: Html.TextArea("Message", "", new { @id = "mytextarea", @title = "Enter the Message" })%>    
<div id="charNum"></div>

jQuery:

$('#mytextarea').keyup(function(){          
      var len = $(this).val().length;
      if (len >= 160) {
          var output = $(this).val().substring(0, 160);
          $(this).val(output);
      } else {
          $('#charNum').html(160 - len);
      }
});

Working Demo

Upvotes: 3

iJade
iJade

Reputation: 23801

Since u haven't posted any code i would tell u how to go forward about implementing this.. simple attach a script on keyup to the textarea like

$('textarea').keyup(function() {
        console.log($(this).val().length);
});

And $(this).val().length should give you the length of the text entered. Then you can implement the way you want it to... Hope it helps

Upvotes: 1

Related Questions