form中限制文本字节数js代码
程序员文章站
2023-11-18 13:59:22
/* value: 值; bytelength:数据库字节长度 title:字段中文名称 attribute:属性...
/*
value: 值;
bytelength:数据库字节长度
title:字段中文名称
attribute:属性名称
使用方法说明:
添加 (1) onkeyup="limitlength(this.value,100,'名称','name')"
(2) id="name" 或【struts标签】styleid="name"
注意:id名称和 attribute属性名称要一样
例子:<textarea name="explain" id="explain" onkeyup="limitlength(value,5,'语义说明','explain')" >
或
<input type="text" name="explain" id="explain" onkeyup="limitlength(value,5,'语义说明','explain')" >
*/
function limitlength(value, bytelength, title, attribute) {
var newvalue = value.replace(/[^\x00-\xff]/g, "**");
var length = newvalue.length;
//当填写的字节数小于设置的字节数
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);//校验点是否为“×”
//if 基点是×; 判断在基点内有×为偶数还是奇数
if (count % 2 == 0) {
//当为偶数时
size = count / 2 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
} else {
//当为奇数时
size = (count - 1) / 2 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
}
alert(title + "最大输入" + bytelength + "个字节(相当于"+bytelength /2+"个汉字)!");
document.getelementbyid(attribute).value = limitvalue;
return;
}
value: 值;
bytelength:数据库字节长度
title:字段中文名称
attribute:属性名称
使用方法说明:
添加 (1) onkeyup="limitlength(this.value,100,'名称','name')"
(2) id="name" 或【struts标签】styleid="name"
注意:id名称和 attribute属性名称要一样
例子:<textarea name="explain" id="explain" onkeyup="limitlength(value,5,'语义说明','explain')" >
或
<input type="text" name="explain" id="explain" onkeyup="limitlength(value,5,'语义说明','explain')" >
*/
function limitlength(value, bytelength, title, attribute) {
var newvalue = value.replace(/[^\x00-\xff]/g, "**");
var length = newvalue.length;
//当填写的字节数小于设置的字节数
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);//校验点是否为“×”
//if 基点是×; 判断在基点内有×为偶数还是奇数
if (count % 2 == 0) {
//当为偶数时
size = count / 2 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
} else {
//当为奇数时
size = (count - 1) / 2 + (bytelength * 1 - count);
limitvalue = value.substr(0, size);
}
alert(title + "最大输入" + bytelength + "个字节(相当于"+bytelength /2+"个汉字)!");
document.getelementbyid(attribute).value = limitvalue;
return;
}