TextArea character counter using jQuery

2019-05-04 06:00发布

问题:

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.

回答1:

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>​


回答2:

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



回答3:

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