Skip to content Skip to sidebar Skip to footer

How Do I Pass A Server Control's Actual Client Id To A Javascript Function?

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);" />

Update

Please check this article: http://www.jagregory.com/writings/how-to-use-clientids-in-javascript-without-the-ugliness/

Also I like this answer

Solution 2:

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:

voidAddClientIDs()
{
    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 :(

Solution 3:

<asp:TextBoxID="txtZip" runat="server" onchange="ZipCode_OnChange(this, txtCity, txtState);">


functionZipCode_OnChange(element, txtCity, txtState) {
    varClientId = element.getAttribute('id'),
        ret = null,
        value = element.value;

    ret = WebService.GetCityAndState(value, OnComplete1, OnError, ClientId);
}

Solution 4:

you can add the onchange event from the code behind in the page_load method.

protectedvoidPage_Load(object sender, EventArgs e)
{
    if (IsPostBack) return;
    txtZip.Attributes.Add("onclick", "ZipCode_OnChange(" + txtZip.ClientID + ")");
}

If you want to pass more than one control along with their ClientID , then this approach is good choice.

I hope this will solve the problem.

Post a Comment for "How Do I Pass A Server Control's Actual Client Id To A Javascript Function?"