我的asp.net網絡應用程序需要一個telerik:RadTextBox,它最多可接受160個字符。每次在此文本框中輸入一個字符時,我都希望我可以鍵入的剩餘字符數作爲標籤顯示在此文本框附近。任何人都可以告訴我應該使用哪個事件並提供JavaScript代碼來執行此操作?顯示剩餘字符數以達到telerik的最大長度:RadTextBox
0
A
回答
1
我已經做了類似這樣的一系列具有文本框在其中用戶控件的東西。我會建議使用onkey和onkey down事件來增加/減少你的計數器。
這是我們使用的JavaScript。
<script type="text/javascript" language="Javascript">
//Character count script!
function textCounter(field, countfield, maxlimit) {
if (countfield == null) { return; }
if (field.value.length > maxlimit)
field.value = field.value.substring(0, maxlimit) + " Characters Remaining";
else
countfield.value = maxlimit - field.value.length + " Characters Remaining";
}
</script>
下面是類似於其下面的計數器字段的文本框。
<telerik:RadTextBox ID="txtTextBox" runat="server" />
<input readonly="readonly" enableviewstate ="false" type="text" runat="server" id="charCount" size="25" name="charCount" tabindex="-1" value=""
style="border: solid 0px white; display:none; background: white; font-size: 11px; color: #FF0000; text-align: right; float:right" />
如果存在文本框的最大長度,則會在onLoad上添加屬性。
txtTextBox.Attributes.Item("onblur") = charCount.ClientID + ".style.display='none';"
txtTextBox.Attributes.Item("onfocus") = charCount.ClientID + ".style.display='block';"
txtTextBox.Attributes.Item("onkeyup") = "textCounter(this, " + charCount.ClientID + "," + myMaxLength.ToString + ");"
txtTextBox.Attributes.Item("onkeydown") = "textCounter(this, " + charCount.ClientID + "," + myMaxLength.ToString + ");"
當這一切被組合時的鞋,如果你已經設置就可以了最大限制,只有當該文本框具有焦點的計數器。一旦焦點消失,腳本onblur再次隱藏文本框。該計數器在onkeyup和onkeydown上被觸發,因此計數將保持準確。它將倒數到0,一旦達到0,用戶將無法輸入更多文本。
0
這裏有一些提示您的問題:
爲了計算的字符數,不包括換行符,您可以使用以下方法:你可以這樣做
<telerik:RadTextBox ID="RTB1" runat="server" TextMode="MultiLine" ClientEvents-OnKeyPress="KeyPress" />
<script type="text/javascript">
function KeyPress(sender, args)
{
var text;
if ($telerik.isIE || args.get_domEvent().rawEvent.keyCode == 0 || args.get_domEvent().rawEvent.keyCode == 13) // 13 : Enter key
{
text = escape(sender.get_value() + args.get_keyCharacter());
}
else
{
text = escape(sender.get_value());
}
while (text.indexOf("%0D%0A") != -1) // IE
{
text = text.replace("%0D%0A", " ");
}
while (text.indexOf("%0A") != -1)
{
text = text.replace("%0A", " ");
}
while (text.indexOf("%0D") != -1)
{
text = text.replace("%0D", " ");
}
var calculatedLength = unescape(text).length;
if (args.get_domEvent().rawEvent.keyCode == 8 && calculatedLength > 0) // 8 : backspace
{
calculatedLength -= 1;
}
document.title = calculatedLength;
}
</script>
這樣。
即使你可以檢查http://www.telerik.com/community/forums/aspnet-ajax/input/counting-characters.aspx瞭解更多詳情。
感謝,
0
使用的onfocus客戶端事件:
EG。
textBox1.Attributes.Add("onFocus", "Counter('textBox1','LabelID',160)");
<script>
function Counter(textboxID, LabelID, MaxCharacters) {
var count = MaxCharacters - document.getElementById(textboxID).value.length;
document.getElementById(LabelID).innerHTML = count;
}
</script>