Binding doesn't work on first KeyPress using jQuery

I have a form where when you press a key or paste text and cut out a text field, the number of remaining characters appears, but when you press it the first time, the function doesn’t work, and on the second, which means in it. My code is below.

$('.Textarea').keypress(function (event) {
    if ($(this).is(':visible')) {
        $(this).bind('paste copy cut keypress', function () {
            var CharsLeft = $(this).parent('div').find('.CharsLeft');
            var Chars = $(this).val().length;
            $('.CharsLeft').text(5000 - Chars);
        });

        if (event.keyCode == 13) {
            var Value = $(this).val();

            $(this).parent('div').find('.SubMessages').append('<div style="border-top:1px solid #EEE; padding:10px 0;">' + 'You: ' + Value + '</div>');
            $(this).val('');

            event.preventDefault();
        }
    }
});
<div class="Message" style="width:100%; text-align:left;">
    <div class="MsgInfo" style="display:block; border-bottom:1px solid #EEE;">
        <span class="InnerMsg">From: Tera</span>
        <span class="InnerMsg">Subject: Welcome To Tera!</span>

        <span class="InnerMsg">When: 2 Hours Ago</span>
        <div style="clear:both;"></div>
    </div>
    <div class="UserMsgContent" style="display:block; padding:10px; line-height:1.5em;">
        <div class="SubMessages">
            <div style="padding:10px 0;">Hello</div>
        </div>
        <textarea style="width:930px;" class="Textarea" placeholder="Reply!" maxlength="5000"></textarea>
        <div style="margin-top:10px;">
            <div class="CharsLeft">5000</div>Characters Left
        </div>
    </div>
</div>
+5
source share
5 answers

Strange behavior.
Binding keyup keydowninstead keypresscorrects it. http://jsfiddle.net/np9w5/1/

+3
source

Use keyupinstead, since reading the length of a value on keypressdoes not give you the exact length of the text.

keypress, textarea , . keyup, :

$(this).bind('paste copy cut keyup', function() {
    var CharsLeft = $(this).parent('div').find('.CharsLeft');
    var Chars = $(this).val().length;

    $(CharsLeft).text(5000 - Chars);    
});

DEMO - keyup


, DEMO, - $('.Textarea').bind(), , $(this) .

+5
$(this).on("keypress", function() {
    var CharsLeft = $(this).parent('div').find('.CharsLeft');
    var Chars = $(this).val().length;

    $(CharsLeft).text(5000 - Chars);    
});

try .on

0
source

Try it.

$(this).keypress(function() {
    var CharsLeft = $(this).parent('div').find('.CharsLeft');
    var Chars = $(this).val().length;

    $(CharsLeft).text(5000 - Chars);    
});
0
source

Why are you ending CharsLeft in another $ ()?

It should be:

CharsLeft.text(5000 - Chars);  

Also, I believe instead of .bind () (which is deprecated), you should use .on ()

Here is jsFiddle with the solution: http://jsfiddle.net/FzWaD/

A couple more bug fixes are included in it.

0
source

All Articles