Since IE8/9 do not support HTML5's maxlength attribute, I need to find a way to prevent pasting too long text into a textarea/input, so I chose to go with the onpaste
-attribute/eventhandler via jQuery, see the example code below:
$(document).ready(function() {
$('textarea[maxlength]').on('paste', function() {
var maxlength = $(this).attr('maxlength');
if (this.value.length >= maxlength) {
this.value = this.value.substr(0,maxlength);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea maxlength="10"></textarea>
The problem is that in IE8/9 when you paste text that exceeds 10 characters, it is fully visible for a moment inside the textarea and only then the event handler cuts off all the text that exceeds the maxlength which is obviously unwanted. It looks like for a short period the pasted text becomes the current value of the textarea - which should never happen.
So I need to intercept the value update of the textarea and check the length of the pasted text before it actually becomes the current value.
What is the best way to achieve this?
You can access the clipboard content with
window.clipboardData.getData('Text')
And manipulate it as necessary before placing it in the textbox.
Be sure to return false or the paste event will fire and replace what you did.
To access the current value, read the innerText value of the textarea.
To get the current cursor position read the selectionStart property. If there is no selection the selectionStart property will give you the current position. If there is a selcetion you can use selectionEnd as well.