Пример #1
0
    private void WriteScripts()
    {
        string script    = string.Format("var {0}_Max = {1};", this.ClientID, MaxLength);
        string scriptKey = string.Format("{0}_script", this.ClientID);

        Javascript.RegisterClientScriptBlock(this.Page, scriptKey, script, true);

        //Page.ClientScript.RegisterClientScriptBlock(typeof(Page), scriptKey, script, true);

        //in case there is 2 LimitTextBoxes only add this function once
        string limitFuncKey = "LimitFunction";

        if (!Page.ClientScript.IsClientScriptBlockRegistered(limitFuncKey))
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("function LimitTextArea(c, counterName, maxLen) {");
            sb.Append("var counter = document.getElementById(counterName);");
            sb.Append("if (counter != null){");
            sb.Append("var len = c.value.length;");
            sb.Append("if (len > maxLen) {");
            sb.Append("c.value = c.value.toString().substr(0, maxLen);");
            sb.Append("} else {");
            sb.Append("counter.innerHTML = maxLen - len;}}}");
            Javascript.RegisterClientScriptBlock(this.Page, limitFuncKey, sb.ToString(), true);
            //Page.ClientScript.RegisterClientScriptBlock(typeof(Page), limitFuncKey, sb.ToString(), true);
        }

        //set the start script
        string startScript = string.Format("if (document.getElementById('{0}') != null) document.getElementById('{0}').innerHTML = {2}_Max - document.getElementById('{1}').value.length;", lblCount.ClientID, txtText.ClientID, this.ClientID);
        string startKey    = string.Format("{0}_start", this.ClientID);

        Javascript.RegisterStartupScript(this.Page, startKey, startScript, true);
        //Page.ClientScript.RegisterStartupScript(typeof(Page), startKey, startScript, true);

        txtText.Attributes.Add("onKeyUp", string.Format("LimitTextArea(this, '{0}', {1}_Max);", lblCount.ClientID, this.ClientID));
    }