Last active
September 21, 2016 05:29
-
-
Save keik/9c3ef6c13dc837a67bb0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Internet Explorer's maxlength bug fix | |
* | |
* @author keik <[email protected]> | |
* @license MIT | |
* | |
* [ref] | |
* https://support.microsoft.com/ja-jp/kb/2922126 | |
* | |
* The workaround in the above article could causes other problems such as render issues. | |
* This patch fix only the maxlength bug. | |
*/ | |
function fixMaxLengthForIE() { | |
'use strict'; | |
var DEFAULT_MAX_LENGTH_VALUE = 524288; | |
// only IE | |
if (window.navigator.userAgent.match(/MSIE|Trident/)) { | |
// remove `maxlength' property which causes the bug, and save the value to `data-maxlength' property. | |
Array.prototype.concat.apply([], document.querySelectorAll('input[maxlength]')).forEach(function (el) { | |
el.setAttribute('data-maxlength', el.maxLength); | |
el.maxLength = DEFAULT_MAX_LENGTH_VALUE; | |
}); | |
// on keypress in input[maxlength], if value exceeds maxlength, prevent default action. | |
document.body.addEventListener('keypress', function (e) { | |
if (Array.prototype.indexOf.call(document.querySelectorAll('input[maxlength]'), e.target) === -1) { | |
return true; | |
} | |
var inputEl = e.target, | |
maxlength = parseInt(inputEl.getAttribute('data-maxlength')), | |
isValid = inputEl.value.length - (inputEl.selectionEnd - inputEl.selectionStart) < maxlength; | |
if (!isValid) { | |
e.preventDefault(); | |
} | |
return isValid; | |
}); | |
// on decide conversion of IME in input[maxlength], cut length of inputed value. | |
document.body.addEventListener('keyup', function (e) { | |
if (Array.prototype.indexOf.call(document.querySelectorAll('input[maxlength]'), e.target) === -1) { | |
return; | |
} | |
var inputEl = e.target, | |
maxlength = parseInt(inputEl.getAttribute('data-maxlength')); | |
if (e.keyCode === 13 /* Enter key code when IME available */) { | |
inputEl.value = inputEl.value.substr(0, maxlength); | |
} | |
}); | |
// on change input[maxlength], cut length of inputed value. | |
document.body.addEventListener('change', function (e) { | |
if (Array.prototype.indexOf.call(document.querySelectorAll('input[maxlength]'), e.target) === -1) { | |
return; | |
} | |
var inputEl = e.target, | |
maxlength = parseInt(inputEl.getAttribute('data-maxlength')); | |
inputEl.value = inputEl.value.substr(0, maxlength); | |
}); | |
} | |
} | |
// apply | |
fixMaxLengthForIE(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment