When working on a project, I write a piece of js for everyone. Regarding the problem of limiting the number of characters in text, it is often used in actual development; the main problem occurs in the restriction of Chinese. The following code solves the verification problem of limiting the number of bytes; just save this code to a js file and Introduce it into the verification page and you can use it! At the same time, I hope everyone will give you strong support and valuable opinions. I will publish more good articles in my spare time in the future, thank you!!
The following is a quote:
/*
value: value;
byteLength: database byte length
title: field Chinese name
attribute: attribute name
Instructions for use:
Add (1) onkeyup="limitLength(this.value,100,'name','name')"
(2) id="name" or [struts tag] styleId="name"
Note: the id name and attribute attribute name must be the same
Example: <textarea name="explain" id="explain" onkeyup="limitLength(value,5,'semantic explanation','explain')" >
or
<input type="text" name="explain" id="explain" onkeyup="limitLength(value,5,'semantic explanation','explain')" >
*/
function limitLength(value, byteLength, title, attribute) {
var newvalue = value.replace(/[^x00-xff]/g, "**");
var length = newvalue.length;
//When the number of bytes filled in is less than the set number of bytes
if (length * 1 <=byteLength * 1){
return;
}
var limitDate = newvalue.substr(0, byteLength);
var count = 0;
var limitvalue = "";
for (var i = 0; i < limitDate.length; i++) {
var flat = limitDate.substr(i, 1);
if (flat == "*") {
count++;
}
}
var size = 0;
var istar = newvalue.substr(byteLength * 1 - 1, 1);//Whether the check point is "×"
//if the base point is ×; determine if there is an × in the base point, whether it is an even number or an odd number
if (count % 2 == 0) {
//When it is an even number
size = count / 2 + (byteLength * 1 - count);
limitvalue = value.substr(0, size);
} else {
//When it is an odd number
size = (count - 1) / 2 + (byteLength * 1 - count);
limitvalue = value.substr(0, size);
}
alert(title + "Maximum input" + byteLength + "bytes (equivalent to "+byteLength /2+" Chinese characters)!");
document.getElementById(attribute).value = limitvalue;
return;
}