Search code examples
asp.nettagsserver-sidedatabound-controlsclientid

How can I get a bound control's client ID with javascript and/or server-side tags?


<asp:DataGrid>
    <ItemTemplate>
        1)
        <asp:TextBox ID="tbComments" onChange="javascript:checkLength(<%# tbComments.ClientId %>);" runat="server"/>
        2)
        <span id="<%# tbComments.ClientId %>Label"></span>
    </ItemTemplate>
</asp:DataGrid>

Any ideas to make the above working (which doesn't :P)?


Solution

  • Change your markup to pass "this" as a reference to the given comments box.

    <asp:TextBox ID="tbComments" 
               onChange="javascript:checkLength(this);" runat="server"/>
    

    Then in your checkLength() function, "e" is a direct reference to the DOM element that raised the onchange event.

    function checkLength(e){
      alert(e.id); //id of the comments box
      //get a reference to the span element immediately after the textbox
      theSpan = e.parentNode.getElementsByTagName("span")[0];
      theSpan.innerHTML = "comments length: " + e.value.length;
    }