1. 程式人生 > >多行文字框textarea的字數控制動態提示。(剩餘字數提醒)

多行文字框textarea的字數控制動態提示。(剩餘字數提醒)

<script type="text/javascript">
        //多行文字輸入框剩餘字數計算
        function checkMaxInput(obj, maxLen) {
            if (obj == null || obj == undefined || obj == "") {
                return;
            }
            if (maxLen == null || maxLen == undefined || maxLen == "") {
                maxLen = 100;
            }

            var strResult;
            var $obj = $(obj);
            var newid = $obj.attr("id") + 'msg';

            if (obj.value.length > maxLen) {	//如果輸入的字數超過了限制
                obj.value = obj.value.substring(0, maxLen); //就去掉多餘的字
                strResult = '<span id="' + newid + '" class=\'Max_msg\' ><br/>剩(' + (maxLen - obj.value.length) + ')字</span>'; //計算並顯示剩餘字數
            }
            else {
                strResult = '<span id="' + newid + '" class=\'Max_msg\' ><br/>剩(' + (maxLen - obj.value.length) + ')字</span>'; //計算並顯示剩餘字數
            }

            var $msg = $("#" + newid);
            if ($msg.length == 0) {
                $obj.after(strResult);
            }
            else {
                $msg.html(strResult);
            }
        }

        //清空剩除字數提醒資訊
        function resetMaxmsg() {
            $("span.Max_msg").remove();
        }
</script>

呼叫方法:

                        
                    <tr>
                        <td align="right" valign="top">
                            備註:
                        </td>
                        <td colspan="5">
                            <textarea id="BZ" name="BZ" style="height: 34px; width: 450px" onkeydown="checkMaxInput(this,80)"
                                onkeyup="checkMaxInput(this,80)" onfocus="checkMaxInput(this,80)" onblur="checkMaxInput(this,80);resetMaxmsg()">
                        </textarea>
                        </td>
                    </tr>

轉自:出處已忘記了,部分加入了我自己的修改。