1,105,556 Community Members

Character count with javascript

Member Avatar
cirbab4
Newbie Poster
7 posts since Jul 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

I have this simple javascript function which counts the number of characters the user is able to enter in a text box/ text area:

http://jsfiddle.net/9XhDK/

how can I cater for any backspaces? (I a user deletes a character the number of characters left increases by 1)?

Thanks

Member Avatar
iamthwee
Posting Sage
7,066 posts since Aug 2005
Reputation Points: 1,307 [?]
Q&As Helped to Solve: 595 [?]
Skill Endorsements: 74 [?]
Featured
 
0
 

maybe
http://jsfiddle.net/9XhDK/1/

Just work on the math bit as it is not accurate

Member Avatar
mmcdonald
Posting Pro in Training
473 posts since Sep 2012
Reputation Points: 28 [?]
Q&As Helped to Solve: 32 [?]
Skill Endorsements: 12 [?]
 
0
 

I've used this one before and it was dead easy to use. It was quite a clean and tidy addition to one of my major forms.

Member Avatar
theHop
Junior Poster in Training
57 posts since Dec 2009
Reputation Points: 18 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
1
 

use keyup instead of keypress. just tried it and it worked better.

$('#txtbox').keyup(function() {

var textLen = $(this).val().length;
var textLeft = parseInt($(this).attr("maxlength")) - textLen;
$('#charCount').text(
    textLeft + ' character' + (textLeft == 1 ? '' : 's') + ' left'
);
});
$('#txtbox').keyup();

I added the maxlength attibute to your textbox and just grapped that in the javascript just to make the acript a bit more re-usable.

Member Avatar
JorgeM
IT Addict
6,414 posts since Dec 2011
Reputation Points: 581 [?]
Q&As Helped to Solve: 963 [?]
Skill Endorsements: 172 [?]
Moderator
Featured
Sponsor
 
0
 

I dont think that line 9 in your sample is needed.. or line 14 from the last jsfiddle example..yes/no?

line 9 - $('#txtbox').keyup();
jsfiddle, line 14 $('#txtbox').keypress();

Member Avatar
theHop
Junior Poster in Training
57 posts since Dec 2009
Reputation Points: 18 [?]
Q&As Helped to Solve: 6 [?]
Skill Endorsements: 0 [?]
 
0
 

that line is just starting the string when the page loads.

Member Avatar
cirbab4
Newbie Poster
7 posts since Jul 2013
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

very helpful all, all I had to do was keyup instead of keypress and worked like a charm. THanks

Member Avatar
stbuchok
Posting Shark
957 posts since May 2011
Reputation Points: 123 [?]
Q&As Helped to Solve: 142 [?]
Skill Endorsements: 2 [?]
 
0
 

keydown would be more accurate as it will fire when someone keeps the button pressed in as well.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article