21

I am working on a project that requires me to count the number of characters entered in a text box and dynamically display the result elsewhere on the page.

As I said, this would preferably be done in jQuery or Javascript.

Thanks in advance.

0

6 Answers 6

64

You could do this in jQuery (since you said you preferred it), assuming you want the character count displayed in a div with id="characters":

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
    var cs = $(this).val().length;
    $('#characters').text(cs);
}

UPDATE: jsFiddle (by Dreami)

UPDATE 2: Updating to include keydown for long presses.

Sign up to request clarification or add additional context in comments.

3 Comments

If someone wants to try this out (like me), I made a jsFiddle: jsfiddle.net/hNn5b
This won't trigger on right-click and paste. You can use $('textarea').on('input', updateCount);
don't windows platforms count a linebreak as 2 charcters? In the example it is counted as one.
11
<script type="text/javascript">
function countChars(countfrom,displayto) {
  var len = document.getElementById(countfrom).value.length;
  document.getElementById(displayto).innerHTML = len;
}
</script>

<textarea id="data" cols="40" rows="5"
onkeyup="countChars('data','charcount');" onkeydown="countChars('data','charcount');" onmouseout="countChars('data','charcount');"></textarea><br>
<span id="charcount">0</span> characters entered.

Plain Javascript.

1 Comment

This is correct but I want to note that it's better to use .textContent instead of .innerHTML if you're adding text content to an element since innerHTML parses data as HTML while .textContent uses straight text which is faster.
11

This is my preference:

<textarea></textarea>         
<span id="characters" style="color:#999;">400</span> <span style="color:#999;">left</span>

Then jquery block

$('textarea').keyup(updateCount);
$('textarea').keydown(updateCount);

function updateCount() {
var cs = [400- $(this).val().length];
$('#characters').text(cs);
}

1 Comment

This won't trigger on right-click and paste. You can use $('textarea').on('input', updateCount);
5

I would like to share my answer which i used in my project and it is working fine.

<asp:TextBox ID="txtComments" runat="server" TextMode="MultiLine" Rows="4" Columns="50" placeholder="Maximum limit: 100 characters"></asp:TextBox><br />
<span id="spnCharLeft"></span>

<script type='text/javascript'>
    $('#spnCharLeft').css('display', 'none');
    var maxLimit = 100;
    $(document).ready(function () {
        $('#<%= txtComments.ClientID %>').keyup(function () {
            var lengthCount = this.value.length;              
            if (lengthCount > maxLimit) {
                this.value = this.value.substring(0, maxLimit);
                var charactersLeft = maxLimit - lengthCount + 1;                   
            }
            else {                   
                var charactersLeft = maxLimit - lengthCount;                   
            }
            $('#spnCharLeft').css('display', 'block');
            $('#spnCharLeft').text(charactersLeft + ' Characters left');
        });
    });
</script>

Source: URL

Comments

3

Though it has been already solved, I'm interested to share something that I have used in one of my projects:

<textarea id="message" cols="300" rows="200" onkeyup="countChar(this)"
          placeholder="Type your message ..." >
</textarea>

<input id="text-character" class="input-mini uneditable-input"
       placeholder="0 Chars" readonly />
<input id="text-parts" class="input-mini uneditable-input"
       placeholder="0 Parts" readonly />
<input id="text-remaining" class="input-medium uneditable-input"
       placeholder="160 Chars Remaining" readonly /> 

Javascript code:

function countChar(val) {

    var len = val.value.length;
    var ctext = len + " Chars";

    var str = val.value;
    var parts = [];
    var partSize = 160;

    while (str) {
        if (str.length < partSize) {
            var rtext = (partSize - str.length) + " Chars Remaining";
            parts.push(str);
            break;
        }
        else {
            parts.push(str.substr(0, partSize));
            str = str.substr(partSize);
        }



    }
    var ptext = parts.length + " Parts";

    $('#text-character').val(ctext);
    $('#text-parts').val(ptext);
    $('#text-remaining').val(rtext);

}

2 Comments

I tried this in JSFiddle but it didn't work.Any idea why?
@unidha you need to include Jquery as well since the $ sign on the bottom 3 lines signifies that Jquery is used to select elements.
2
<script Language="JavaScript">
<!-- 
function Length_TextField_Validator()
{
   var len = form_name.text_name.value.length; //the length
   return (true);
}
-->
</script>

<form name="form_name" method="get" action="http://www.codeave.com/html/get.asp" 
onsubmit="return Length_TextField_Validator()">
<input type="text" name="text_name">
<input type="submit" value="Submit">
</form>

Source(s) : Text Validation

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.