Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind doesn't work on first KeyPress using jQuery

I have a form that when a key is pressed or text pasted and cutted from a textarea the amount of characters left will appear but on the first keypress the function doesnt work but on the second one and so in it does. 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>
like image 887
Moussa Harajli Avatar asked Mar 12 '13 23:03

Moussa Harajli


2 Answers

Use keyup instead as reading the length of the value on keypress doesn't give you the accurate length of the text.

When you press the key the keypress event fires but your textarea has not been updated with the new text until after the key is released. Use keyup, similar to the below:

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

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

DEMO - Using keyup instead


The only thing I changed in the DEMO is the binding selector to $('.Textarea').bind() to get it to work in the fiddle as $(this) would not work in the fiddle.

like image 53
Nope Avatar answered Nov 05 '22 23:11

Nope


Strange behavior.
Binding keyup keydown instead of keypress fixes it. http://jsfiddle.net/np9w5/1/

like image 23
Pierre Avatar answered Nov 05 '22 22:11

Pierre