Word counter in textarea error

188 Views Asked by At

Hello I have an error on the word counter for a textarea and can't seem to see the problem. It shows a huge number ("Remaining characters :2147483645") even though the word limit is 250. This is my code:

<textarea class="input-textarea" minlength="0" rows="8" cols="40" data-character-limit="250"></textarea>

JS:

$('form textarea[maxlength].input-textarea').off("keyup.default37").on("keyup.default37", function(e){
    //if contact us from the order details ; do not show wordcounter
    if($('#dwfrm_contactus_comment').length) {
        return;
    }

    if ($(this).parent().find('span.wordcounter').length==0) {
        $('<span/>').attr('class','wordcounter error').appendTo($(this).parent());
    }

    if ($(this).val().length < this.maxLength) {
        $(this).parent().find('span.wordcounter').html(app.resources.TEXTAREA_REMAINING_MESSAGE+($(this).attr('maxlength')-$(this).val().length));
    }
    else if ($(this).val().length >= this.maxLength) {
        $(this).val($(this).val().substr(0,this.maxLength));
        $(this).parent().find('span.wordcounter').html(app.resources.TEXTAREA_MAXIMUM_LENGTH);
    }
});

Please note that the html is not the exact one, as I am working on an eccomerce platform which has different syntax. Thanks

1

There are 1 best solutions below

2
On

Why not with simple approach:

Example HTML

<div >
    <textarea class="input-textarea" minlength="0" rows="8" cols="40" data-character-limit="25"></textarea>
    <span class="chars-left"></div>
</div>

And JS

$(document).ready(function(){
    $('.chars-left').text($('textarea').data('character-limit'));
    $('textarea').on('keyup', function(e){
        if($(this).val().length > $(this).data('character-limit')) {
            $(this).val($(this).val().substr(0,$(this).data('character-limit')));
        }
        var left = $('textarea').data('character-limit') - $(this).val().length;
        $('.chars-left').text(left);
    });
});

And working fiddle