0

I'm trying to simulate the HTML5 behavior for maxlength for a textarea in lower versions of Internet Explorer (ie8, ie7):

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
 <textarea maxlength="200"></textarea>

 <script type="text/javascript">
 $(document).ready(function() {
    $(document).delegate('textarea[maxlength]', 'keyup paste change', function(e) { 

        var limit = parseInt($(this).attr('maxlength'));  
        var text = $(this).val();  
        var chars = text.length;  

        if(chars > limit){  
            var new_text = text.substr(0, limit);  

            $(this).html(new_text);  
        }  
    });  
});
</script>

The problem behavior is that if I enter in 201 Japanese characters, the textarea will adjust the text to only show the first 200 characters, as expected, but then when the textarea loses focus by my clicking off of it, the textarea will only show the 201st Japanese character. This problem does not happen if you enter in the 201st character as an English character. I'm inputing the Japanese characters using the Windows Japanese IME, in case that's a relevant detail.

ETA: I believe now this is a problem with Javascript not playing nice with the Japanese IME, but I still have no idea how to go about fixing it.

Kai
  • 3,803
  • 1
  • 16
  • 33
  • Use the `keypress` event instead of `keyup`. Also, you could use the `input` event in modern browsers and the `propertychange` event in IE to detect changes to the textarea's `value` property. Example: http://stackoverflow.com/a/14029861/96100 – Tim Down Jul 07 '14 at 22:46
  • use val() instead of html() – dandavis Jul 07 '14 at 23:03

1 Answers1

2

This behavior is almost certainly due to the Japanese IME changing the input after the various Javascript events are fired. The best solution I've found is to change the above code so that it is triggered by the "blur" event instead, as "blur" seems to always happen after the Japanese IME has finished editing.

Kai
  • 3,803
  • 1
  • 16
  • 33