I have the following textbox server control in my web page:
<asp:TextBox ID="txtZip" runat="server" onchange="ZipCode_OnChange(this, <%= txtZip.ClientId %>, txtCity, txtState);/">
When the page renders, it is built including the following:
<input name="txtZip" type="text" id="txtZip" onchange="ZipCode_OnChange(this, <%= txtZip.ClientId %>, txtCity, txtState);" />
I'm trying to pass the text box's client IDas the 2nd param to this Javascript function:
function ZipCode_OnChange(txtZipCode, ClientId) {
var ret;
ret = WebService.GetCityAndState(txtZipCode.value, OnComplete1, OnError, ClientId);
}
How do I get it to, on the server, evaluate the texbox's control and to pass that literal string to the Javascript function?
Put the <%= txtZip.ClientId %>
between single quotes, to be like this:
'<%= txtZip.ClientId %>'
<asp:TextBox ID="txtZip" runat="server" onchange="ZipCode_OnChange(this, '<%= txtZip.ClientId %>', txtCity, txtState);" />
Update
Please check this article: http://www.jagregory.com/writings/how-to-use-clientids-in-javascript-without-the-ugliness/
Also I like this answer
There are a lot of ways to fix this, but I find the simplest thing to do in the general case is use the ScriptManager to include a separate script at the top of my pages specifically for the purpose of adding ClientIDs:
void AddClientIDs()
{
var clientIDs = new StringBuilder();
var declaration = "var {0}={1};";
clientIDs.AppendFormat(declaration, "txtZip", txtZip.ClientID);
ClientScript.RegisterClientScriptBlock(this.GetType(), "ClientIDs", clientIDs.ToString(), true);
}
Call that in the PreRender event (somewhere after databinding). Then, if you want to get a little fancy you can easily adapt the method up to accept an IEnumerable or params array of controls, and let it use the control names for the javascript variable names. Sometimes I do that, but it's usually simple enough to just add what I need directly to the method.
Even this is somewhat awkward, because controls including in other naming containers (like grids) can still cause problems. I'd like to see the ASP.Net team build something like this directly into the framework soon, but I'm not really expecting it :(
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With