Reputation: 151
In this scernario, I have a textbox and a label of which the label is a countdown of the remaining characters available in the textbox. E.g. "239 characters remaining".
I personally want to use the javascript function a couple of times, so I want to pass to the variables to the function. These being, maxlength (for length), textbox (for the field) and label (for the counter label).
However, the issue I have is that this is simply not working. Just to make sure it wasn't just an IE thing, I tested it in Firefox 18 and it's also producing the same where where label does not change... It's almost like the onKeyUp method is note being called.
Anyways my code.
JavaScript
<script type="text/javascript">
function countCharacters(textbox, label, maxcount) {
var count = parseInt(document.getElementById(textbox).value.length);
document.getElementById(label).innerHTML = maxcount - count;
}
Label and Textbox
<asp:TextBox ID="tbComment01" runat="server" CssClass="txt" TextMode="MultiLine" Width="500px" Visible="false" MaxLength="500"></asp:TextBox>
<br />
<asp:Label ID="lbCommentCount01" runat="server" Text="Label" Visible="false" CssClass="size11_text_blurb"></asp:Label>
Code Behind
tbComment01.Attributes.Add("onKeyUp", "countCharacters(" + tbComment01.ClientID + "," + lbCommentCount01.ClientID + ", 500)");
Cheers all!
Trent
Upvotes: 0
Views: 667
Reputation: 26386
The problem is because there were no quotes on the parameters to your function. Therefore it was passing the HTML element objects and not their Ids. You were thus using getElementById
on an object and not the ID [which should be a string]
Before, your function looked like
onKeyUp="countCharacters(tbComment01,lbCommentCount01, 500)"
therefore passing HTMLTextAreaElement
instead of string "tbComment01"
And should be
onKeyUp="countCharacters('tbComment01','lbCommentCount01', 500)"
This should fix it, note that I have added the single quotes from code-behind
tbComment01.Attributes.Add("onKeyUp", "countCharacters('" + tbComment01.ClientID + "','" + lbCommentCount01.ClientID + "', 500)");
OR better
tbComment01.Attributes.Add("onKeyUp",String.Format("countCharacters('{0}','{1}', 500) ", tbComment01.ClientID, lbCommentCount01.ClientID)
Upvotes: 1
Reputation: 752
It looks like this is due to lbCommentCount01 still being Visible="false"
serverside, when Visible="false"
, controls are not rendered to page. (This is to save bandwidth.)
If you want to make the control initially invisible, but turn it visible in javascript, make sure to use style="display:none;"
and in the code remove that with:
document.getElementById('yourid').style.display = '';
Upvotes: 1