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>
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.
Strange behavior.
Binding keyup keydown
instead of keypress
fixes it. http://jsfiddle.net/np9w5/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With