5

I'm having trouble figuring out why my JavaScript is not working right. Its with j Query and its supposed to select all the text area tags and then for each text area count the number of characters typed in them and then not allow the user to enter any more after it hits the max length, also showing a character counter under each text area box. What its doing is only showing the characters remaining but not decrementing after each key pressed and also not stopping when it hits the max length. It also doesn't select all of the text areas, it only takes the first one it finds.

Here is my TextAreaCounter.js

$(document).ready(function){
var $texts = $('textarea[maxlength]');
$texts.each(function){
  $var $this = $(this),
  max = $(this).attr('maxlength'),
  textId = $(this)attr.('id'),
  $parent = $this.parent(),
  countId = textId+'-count';

$div = $('<div>Characters Remaining: </div>').addClass('count-down').insertAfter($this);
$input = $('<input></input>').attr({
    type:"text",
    readOnly: "readOnly",
    value: max,
    id: countId
    }).css({
      width: "25px"
      marginTop: "5px"
      marginBottom: "10px"
    }).addClass('readOnly').appendTo($div);

$this.on({
  keyup: function(){
    val = $this.val(),
    countVal = $('#'+countId).val(),
    if(val.length > max){ 
      $this.val(val.substr(0,max));
      alert('Max length exceeded: ' +max);
      return false;
    }else{
      $('#'+countId).val(max-val.length);
    }
  },
  blur: function(){
    val=$this.val();
    if(val.length > max){
      $this.val(val.substr(0,max));
      alert('Max length exceeded: ' +max);
      return false;
    }else{
      $('#'+countId).val(max-val.length);
    }
  }
});
});
});  

When i added some alerts, not shown in the code here, it showed that it was not getting to the this.on section with the keyup event. I included this external js file to a jsp file which my page is made and has my text areas in. I also add an id and maxlength attribute to the textarea element. Any help would be great thank you.

2
  • yeah sorry it was just a typo in the question
    – Sheldor
    Aug 7, 2012 at 4:53
  • Note that truncating the string back to the maximum allowed length as the user types is pretty clunky - better to change the background colour or otherwise highlight it as an error and leave it to the user to fix. Otherwise the user will get confused when they try to edit the beginning or middle of the field and you start deleting extra characters from the end...
    – nnnnnn
    Aug 7, 2012 at 4:56

3 Answers 3

2

Oh man - Donno why you need the code above if you can do this: http://jsfiddle.net/btyCz/

Limited demo http://jsfiddle.net/jnXEy/ ( I have set the limit to 20) feel free to play around.

Please lemme know if I missed anythig, but the below should help:)

You can always put the check on the length to limit it.

code

$('#myInput').keyup(function() {
    $('#charCount').text( this.value.replace(/{.*}/g, '').length );
});​

HTML

<textarea id="myInput"></textarea> <br>
Counter: <span id="charCount"></span>​
5
  • 1
    What's that regex replace for? I don't think it's doing what you intend it to - type "asdf{sdf}asdf" in your fiddle and see what the count is...
    – nnnnnn
    Aug 7, 2012 at 4:52
  • what is the use of replace(/{.*}/g, '') in $('#charCount').text( this.value.replace(/{.*}/g, '').length ); Aug 7, 2012 at 4:54
  • 1
    @nnnnnn saweet bruv! :) howz you? I will replace replace soon :)
    – Tats_innit
    Aug 7, 2012 at 4:54
  • @shrujanshetty regular-expressions.info :) quite good, g = global, wildcard notations * and et al
    – Tats_innit
    Aug 7, 2012 at 5:03
  • @Tats_innit That is easier thank you! :) but i guess i still don't see how i can make it limit to a specific number of chars with this code u.(really tired and can't think...) and also why my code only selected the first text area tag instead of all of them.
    – Sheldor
    Aug 7, 2012 at 5:04
1

You should go through

http://www.mediacollege.com/internet/javascript/form/limit-characters.html

to limit the charecters in text area

A simple way to limit the number of charecters is

<textarea maxlength="50">
Enter text here
</textarea>

for more data go to

http://www.w3schools.com/html5/att_textarea_maxlength.asp

0

Your code has many syntax errors. Try this now:

$(document).ready(function () { // bracket was missing here...
    var $texts = $('textarea[maxlength]');
    $texts.each(function () { // bracket was missing here...
        var $this = $(this), // incorrect variable declaration here...
        max = $this.attr('maxlength'),
        textId = $this.attr('id'), // incorrect method call here...
        $parent = $this.parent(),
        countId = textId + '-count',

        $div = $('<div>Characters Remaining: </div>').addClass('count-down').insertAfter($this),
        $input = $('<input></input>').attr({
            type: "text",
            readOnly: "readOnly",
            value: max,
            id: countId
        }).css({
            width: "25px", // missing comma here...
            marginTop: "5px", // missing comma here...
            marginBottom: "10px"
        }).addClass('readOnly').appendTo($div);

        $this.on({
            keyup: function () {
                var val = $this.val(),
                countVal = $('#' + countId).val(); // must have semicolon here...
                if (val.length > max) {
                    $this.val(val.substr(0, max));
                    alert('Max length exceeded: ' + max);
                    return false;
                } else {
                    $('#' + countId).val(max - val.length);
                }
            },
            blur: function () {
                var val = $this.val();
                if (val.length > max) {
                    $this.val(val.substr(0, max));
                    alert('Max length exceeded: ' + max);
                    return false;
                } else {
                    $('#' + countId).val(max - val.length);
                }
            }
        });
    });
});

http://jsbin.com/uzohuv/3

3
  • Thank you so much :) but can you show say which line numbers had the syntax errors because i dont see them. (I did accidently have an extra single quote in var $texts = $('textarea[maxlength]'); in my explanation but i fixed that. Thanks again
    – Sheldor
    Aug 7, 2012 at 5:18
  • I've updated code with comments where I've changed your code, as far as I remember.
    – Ketan Modi
    Aug 7, 2012 at 5:32
  • Ah yeah all those are just stupid typos i made in this question, not actually my code. But im guessing it has to do with how its reacting with my jsp page since it seems to be working for you. Also is it working with multiple textareas on one page for you? it only attempts to work for the first text area element in my jsp page
    – Sheldor
    Aug 7, 2012 at 6:02

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.