2

I'm tring to prevent users entering any more input into a textarea when the char count reaches a certain value.

My code works fine in Chrome, Safarai and Firefox.

But the preventDefault method will not work for me in any version of IE.

I have found many similar topics on SO about this and included the most common suggestion:

  • Performing a check to make sure preventDefault exists. If it doesn not exist use IEs returnValue=false. The problem is returnValue=false will not work either.

Any suggestions?

// Attach textarea char counter to all textarea's with class of 'textarea-char-count'
$('.textarea-char-count').live("keyup", function(event) {
    MYAPP.COMMON.textareaCounter(this, event);
}); 

// Attach textarea char counter to element
MYAPP.COMMON.textareaCounter = function(element, evt) {

    //Get char limit
    var limit = $(element).attr("maxlength");

    // get current character count
    var current = $(element).val().length;

    // if current character count is greater than or equal to the character limit
    if(current >= limit) {
        // prevent further characters from being entered apart from the 
        // Delete and Backspace keys
        if(evt.which != 0 && evt.which != 8)
        {
            if (evt.preventDefault) {
                evt.preventDefault();
            }
            else {
                evt.returnValue = false;
            }
        }
    }

    // add the remaining character count to our span
    $(element).parent().next().show().text( current + " / " +  limit);
}
Thomas Buckley
  • 5,836
  • 19
  • 62
  • 110

2 Answers2

3

Change the event from keyup to keydown, it will work

Demo: Fiddle with keyup

Demo: Fiddle with keydown

The keypress event will not work since IE and Chrome does not fire it on backspace and delete

Note: The counter still behave oddly.

There are some more changes that can be done, ex move from live to on since live is deprecated

Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Any ideas why keydown works and keyup does not? Keydown behaves very oddly as you suggested. Currently working on solution with keydown that will have some sort of decent user experience! – Thomas Buckley Mar 08 '13 at 14:18
  • I think, it is because by the time `keyup` is processed the pressed key is already added to the inputs value, so you cannot revert it – Arun P Johny Mar 08 '13 at 15:09
1

live is depreciated and use keypress

$('body').delegate(".textarea-char-count","keypress", function(event) {
        MYAPP.COMMON.textareaCounter(this, event);
    }); 
coolguy
  • 7,866
  • 9
  • 45
  • 71