最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - TextArea character counter using jQuery - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Aug 7, 2012 at 4:46 SheldorSheldor 611 silver badge5 bronze badges 2
  • yeah sorry it was just a typo in the question – Sheldor Commented 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 Commented Aug 7, 2012 at 4:56
Add a ment  | 

3 Answers 3

Reset to default 2

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

Limited demo http://jsfiddle/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>​

You should go through

http://www.mediacollege./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./html5/att_textarea_maxlength.asp

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 ma here...
            marginTop: "5px", // missing ma 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./uzohuv/3

发布评论

评论列表(0)

  1. 暂无评论