日期:2014-05-18  浏览次数:20605 次

如何check jsp文字框中可以输入字符串的byte数
页面上有一个text框。
<input type=text size=30 Maxlength="20" ID="value" name="value">
这样的话里面既可以输入20个半角,又可以输入20个全角。
我想要的样子是:不管全角半角,只允许输入20个byte。否则弹出message。
该怎么实现呢?

------解决方案--------------------
HTML code
 <html> 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gbk" />
<title>试试 </title>
</head>

<script type="text/javascript">
var INPUT_BORDER_COLOR = 'mediumseagreen';
var INPUT_BORDER_ERROR = 'red';
var INPUT_BGCOLOR = 'lemonchiffon';
var INPUT_DEFAULT_BGCOLOR = 'white';
var INPUT_DEFAULT_BORDER_COLOR = 'silver';

window.$ = function(id) {
if(typeof id == 'string') {
  return document.getElementById(id);
}
return id;
}

function chanageBackColor(tag) {
var txts = document.getElementsByTagName(tag);
for(var i = 0; i < txts.length; i++) {
  if(tag == 'input' && txts[i].type != 'text') {
  continue;
  }
  txts[i].isfocus = false;
  txts[i].onmouseover = function() {   
  this.style.backgroundColor = INPUT_BGCOLOR;
  }
  txts[i].onfocus = function() {
  this.isfocus = true;
  this.style.backgroundColor = INPUT_BGCOLOR;
  if(!this.hasError) {
    this.style.borderColor = INPUT_BORDER_COLOR;
  }
  }
  txts[i].onmouseout = function() {
  if(!this.isfocus) {
    this.style.backgroundColor = INPUT_DEFAULT_BGCOLOR;
  }
  }
  txts[i].onblur = function() { 
  this.style.backgroundColor = INPUT_DEFAULT_BGCOLOR;
  if(!this.hasError) {
    this.style.borderColor = INPUT_DEFAULT_BORDER_COLOR;
  }
  this.isfocus = false;
  }
}
}

window.onload = function() {
chanageBackColor('input');
chanageBackColor('textarea');
}

var checkObjs = [
{id: 'name',  len: 20,  eid: 'nameMsg', msg : '名字不能超过 20 个字节'},
{id: 'page',  len: 50,  eid: 'pageMsg', msg : '主页不能超过 50 个字节'},
{id: 'code',  len: 6,  eid: 'codeMsg', msg : '验证码不能超过 6 个字符'},
{id: 'comment', len: 100, eid: 'commentMsg', msg : '评论内容不能超过 100 个字节'}
];

function tooLong(s, length) {
var len = 0;
for(var i = 0; i < s.length; i++) {
  if(s.charCodeAt(i) > 0xff) {
  len += 2;
  } else {
  len++;
  }
}
return len > length;
}

function check() {
var b = true;
for(var i = 0; i < checkObjs.length; i++) {
  var obj = checkObjs[i];
  var c = tooLong($(obj.id).value, obj.len);
  b = b && !c;
  if(c) {
  $(obj.eid).innerHTML = obj.msg;
  $(obj.id).style.borderColor = INPUT_BORDER_ERROR;
  $(obj.id).hasError = true;
  } else {
  $(obj.eid).innerHTML = '';
  $(obj.id).style.borderColor = INPUT_DEFAULT_BORDER_COLOR;
  $(obj.id).hasError = false;
  }
}
if(!b) {
  alert('输入错误啦,不能提交哦 :-)');
}
return b;
}
</script>

<style type="text/css">
form table {
fo