3

Is there any way to tell from a given keydown event whether the owner input[type=text] or textarea will decrease or increase in length after it's applied?


Background: have an HTML5 site (<!DOCTYPE html>) that has to support IE 8 and 9 users as the primary consumer. On some pages, I have <textarea> elements with maxlength="100" attributes. IE does not recognize the maxlength attribute, and allows more than 100 characters to be entered into the textarea.

I have not seen a shim that limits the character length of a textarea in IE with the same keyboard behavior as a input[type=text] element.

For that reason, I'm trying to write one.

Existing implementations look something like this:

$('textarea[maxlength]').on('keydown keyup blur', function(e) {
    var $this = $(this),
        maxlen = $this.attr('maxlength'),
        val = $this.val();

    if (val.length > maxlen) {
        $this.val(val.substr(0, maxlen));
    }
});

The problem with above implementation is that you can type or paste 11 characters and the value is not trimmed to the maxlength until after the value has changed. I would like to prevent a change before the value changes, to better align with input[type=text,maxlength] behavior.

user979672
  • 1,803
  • 3
  • 23
  • 32

2 Answers2

1

You're already listening on keydown and keyup events - there's nothing else you can do, unfortunately. keypress events might add something more, but I think they trigger along with keyup so probably not.

One issue with the above code is that if you right-click and paste (or do so through the edit menu) then it won't help.

One possible workaround is to use CSS to hide the textarea off-screen, then put another "false" textarea which mimics it in place. When the user types, have it action in the off-screen one, and then copy what you want to the "false" one on-screen. In practice, I'm not sure how this would work with instances like the right-click > paste situation - it might take a lot of messing around.

SpoonNZ
  • 3,780
  • 1
  • 20
  • 25
0

Your problem is that your internet explorer doesn't even put the value of maxlength into html, try to hard code that into javaScript, for example;

 $(document).on('input keyup', 'textarea', function(e) {
        // maxlength attribute does not in IE prior to IE10
        // http://stackoverflow.com/q/4717168/740639
        console.debug("here")
        var $this = $(this);
        var maxlength = 255;
        if (!!maxlength) {
            var text = $this.val();

            if (text.length > maxlength) {
                // truncate excess text (in the case of a paste)
                $this.val(text.substring(0,maxlength));
                e.preventDefault();
            }

        }

    });
Aladdin
  • 1,207
  • 2
  • 16
  • 26