Yes, along the way we develop websites/apps with more customized requirements, we discovered more cross browser issues that might not be significant. Okay, here’s the scenario…
A form has a textarea (not textbox) and it is required to have max characters limitation imposed. Textareas do not support “maxlength” property. Thus, the only way is via Javascript to check the texts input upon “onkeyup” event.
Now, here comes the issue. IE/Opera and Firefox/Chrome treats newlines differently…. lets say you typed 5 characters and then enter newline once. IE/Opera will calculate as (5 chars + \r\n + 5 chars), so total 12 chars… But Firefox/Chrome treats newline as 1 char, so? 11 chars it reads. Quite odd… but this issue could be a major chaos especially if you are to store the value of textarea into DB with specific length…
Thus, the only way to work around is using JavaScript to detect the browser type and play around with the character lengths.
Here’s a snippet on how to perform character limits for textarea:
var charLen = 500; // Maximum word length
function checkLength(obj, event) {
var str = obj.value;
var strLen = 0;if (!str) {
strLen = 0;
}
else {
var lns = str.match(/\r|\n|\r\n/g);if (lns) {
if (navigator.userAgent.indexOf(’MSIE’) != -1 || navigator.userAgent.indexOf(’Opera’) != -1) {
strLen = str.length - (lns.length / 2);
}
else {
strLen = str.length;
}
}
else {
strLen = str.length;
}
}if (strLen = 37 && keyCode <= 40) || (keyCode == 8 ) || (keyCode == 46))
return true;
else
return false;
}}
function checkPasteLength(obj) {
var str = obj.value;
var strLen = 0;if (!str) {
strLen = 0;
}
else {
var lns = str.match(/\r|\n|\r\n/g);if (lns) {
if (navigator.userAgent.indexOf(’MSIE’) != -1 || navigator.userAgent.indexOf(’Opera’) != -1) {
strLen = str.length - (lns.length / 2);
}
else {
strLen = str.length;
}
}
else {
strLen = str.length;
}
}if (strLen<= charLen) {
obj.value = str;
return true;
}
else {
obj.value = str.substring(0, charLen);
return false;
}}
onkeypress=”return checkLength(this,event)”
onchange=”return checkPasteLength(this)”
Tags: JavaScript