问题
I'm not sure if I have the last bit right? I changed the max length of the textbox to 140. I can't seem to use TextLength
. Help please?! I have this so far:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = textBox.MaxLength - textBox.TextLength;
}
回答1:
characterCountLabel.Text
is in string format. So you might want to convert it before you set its value like this:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = (textBox.MaxLength - textBox.Text.Length).ToString();
}
I think you are trying to display the remaining characters the user can input to your text box? I suggest that you can set the limit as constant like this:
protected void textBox_TextChanged(object sender, EventArgs e)
{
characterCountLabel.Text = (140 - textBox.Text.Length).ToString(); // in here 140 is your limit
}
If you are using ASP.NET in C#. Don't limit yourself from using javascript like in this link
回答2:
I think this will be a better answer...
Header code:
<script language="javascript" type="text/javascript">
function getCountDown()
{
//Get the Textbox control
var textField = document.getElementById("<%#TextBox1.ClientID %>");
//Do the math of chars left and pass the value to the label
document.getElementById('<%#Label1.ClientID %>').innerHTML = textField.maxLength - textField.value.length;
return false;
}
</script>
ASP code:
<asp:TextBox ID="TextBox1" runat="server" MaxLength="729" Height="80px"
Width="591px" onkeyup="getCountDown();" ClientIDMode="Static"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="" ClientIDMode="Static"></asp:Label>
It is important to set the TextBox
and Label
control's property as ClientIDMode="Static"
otherwise the control name will not be found on the javascript.
CS code:
protected void Page_Load(object sender, EventArgs e)
{
Page.Header.DataBind();
}
That's it for a SingleLine
TextBox.
Now for a MultiLine
TextBox
you need to add this on your Page_Load()
so the maxLength
takes the TextBox1.MaxLength
value.:
this.TextBox1.Attributes.Add("maxLength", TextBox1.MaxLength.ToString());
Also the MaxLength
property of the TextBox
doesn't work when is on Multiline
mode so you need to add on your javascript getCountDown()
function the following lines:
// Check if user is entering more than the limit of characters
if (textField.value.length >= textField.maxLength) {
// Cut extra text
document.getElementById("<%#TextBox1.ClientID %>").innerHTML = textField.value.substring(0, textField.maxLength);
}
add them right after the var textField = document.getElementById("<%#TextBox1.ClientID %>");
line. This is to prevent the user from entering more characters than the MaxLength
value.
Pablo
来源:https://stackoverflow.com/questions/16908006/how-to-display-remaining-textbox-characters-in-a-label-in-c