开发者

Issue with text area key down event using jQuery

开发者 https://www.devze.com 2023-03-01 00:43 出处:网络
We\'re having problems trying to implement a word counter similar to the one on twitter which decrements when the user types in the text field. Unfortunately it\'s quite glitchy as once you\'ve delete

We're having problems trying to implement a word counter similar to the one on twitter which decrements when the user types in the text field. Unfortunately it's quite glitchy as once you've deleted all the characters via backspace it displays that you only have 84 characters left (unless you hit backspace again). If you it t开发者_开发技巧he delete button the counter goes down even when it has removed nothing from the screen at the end of the text(I'm guessing it removes the 'invisible' character that is causing it to say 84 instead of 85 in the example before). All I want if for it to operate like the one on twitter

/* Limit textarea for cancelation policy to 85 characters*/

        $('.counter').text(85-($('#txtCpolicy').val().length));
        $('#txtCpolicy').keydown(function(e) {
            var current = $(this).val().length;
            $('.counter').text(85 - ($('#txtCpolicy').val().length));
            if(current >= 85) {
                if(e.which != 0 && e.which != 8) {
                    e.preventDefault();
                }
            }
        });

Hope you can help


Change your code to keyup instead of keydown. Keydown triggers before the text is added to the textarea. Seems to work once you change it.

0

精彩评论

暂无评论...
验证码 换一张
取 消