日期:2014-05-16  浏览次数:20313 次

js神奇的限制文本框字数(区分中英文--全)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="限制用户输入字数.aspx.cs" Inherits="限制用户输入字数" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function showNum(){
var strTemp=document.getElementById("desc").value;
var sum=0;
for(var i = 0;i<strTemp.length;i++){
if((strTemp.charCodeAt(i)>=0)&&(strTemp.charCodeAt(i)<=255)){?
sum=sum+1;??
}else{??
sum=sum+2;??
}???
if(sum>600){
var str=strTemp.substring(0,i);
document.getElementById("desc").value=str;
document.getElementById("areamsg").innerHTML="<font color='red'>已经输入300字符</font>"+"i"+i+"? sum"+sum;
? break;
}else{
? document.getElementById("areamsg").innerHTML=sum;
? }
? }
}

?

function webkeyword_onkeyup(e){
???$("#showTextNum").html($("#WebKeyWord").val().length);
??}

??$(document).ready(function(){
???$("#showTextNum,#showTextNum1").css({color:"red"});
???$("#showTextNum").html($("#WebKeyWord").val().length);
??})
</script>

</head>

<body>
<form id="form1" runat="server">
<textarea id="desc" runat="server" rows="4" cols="20" onchange="showNum();"></textarea>
<span id="areamsg"></span>
<asp:TextBox ID="WebKeyWord" runat="server" CssClass="addinput" Width="400px"
??????????????????? Rows="5" TextMode="MultiLine"></asp:TextBox> <span id="showTextNum"></span>&nbsp;建议<font color="#008000">100</font>以内。
</form>

</body>
</html>

------后台代码

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class 限制用户输入字数 : System.Web.UI.Page
{
??? protected void Page_Load(object sender, EventArgs e)
??? {
??????? WebKeyWord.Attributes["onkeyup"] = "webkeyword_onkeyup(event)";
??????? desc.Attributes["onkeyup"] = "showNum(event)";
??????
??? }
}