1. 程式人生 > >js動態約束文字框錄入文字長度大小

js動態約束文字框錄入文字長度大小

 <script type="text/javascript">
        var Count = 0;
        function CountStrByte(Message, Total, Used, Remain) { //位元組統計
            var ByteCount = 0;
            var StrValue = Message.value;
            var StrLength = Message.value.length;
            var MaxValue = Total;
            if
(Count != StrLength) { // 在此判斷,減少迴圈次數 for (i = 0; i < StrLength; i++) { ByteCount = ByteCount + 1; if (ByteCount > MaxValue) { Message.value = StrValue.substring(0, i); alert("最多不能超過 " + MaxValue + " 個字元!\n"
); ByteCount = MaxValue; break; } } Used.innerText = ByteCount; Remain.innerText = MaxValue - ByteCount; Count = StrLength; } } function initPage
() {
CountStrByte(document.all.txtRemark, document.all.total.innerText, document.all.used, document.all.remain) }
</script>
<body onload="initPage()">
<table>
<tr class="contentAlign">
                    <td>備註</td>
                    <td colspan="5">
                        <asp:TextBox ID="txtRemark" runat="server" Style="width: 98%; height: 80px; margin-top: 5px; font-size: 12px;" TextMode="MultiLine"
                            onkeyup="CountStrByte(document.all.txtRemark,document.all.total.innerText,document.all.used,document.all.remain)"
                            onkeypress="CountStrByte(document.all.txtRemark,document.all.total.innerText,document.all.used,document.all.remain)"></asp:TextBox>
                        <br />
                        <div style="color: Gray;">
                            &nbsp;最多可輸入 <span style="color: Red;" id="total" name="total">250</span>個字,
                      您已經輸入 <span style="color: Red;" id="used" name="used">0</span> 個字元,
                      還可以輸入<span style="color: Red;" id="remain" name="remain"> 250 </span>個字元。
                        </div>
                    </td>
                </tr>
</table>
</body>

這裡寫圖片描述