JavaScript getElementById for ASP.NET Control returns null?

Wafaa picture Wafaa · Jul 13, 2009 · Viewed 52.6k times · Source

I use JavaScript and this error appears for me during execution:

Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

this my code:

<asp:Content ID="content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<script language="javascript" type="text/javascript">
    function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById("btnAlelrt").click();

        }       
}
</script>
<asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="uxContainer" runat="server">
    <ContentTemplate>
 <table> 
<tr>
        <td>
        <asp:Button ID="uxTransfer" runat="server" Text="Transfer" OnClick="uxTransfer_Click" /> 
        <asp:Button ID="btnAlelrt" runat="server" Text="GetDetails" OnClick="btnAlelrt_Click" />       
        </td>
        </tr>
</table>
    </ContentTemplate>
<Triggers>
    <asp:PostBackTrigger ControlID="uxTransfer" />    
    </Triggers>
    </asp:UpdatePanel>

 </asp:Content>

Answer

kemiller2002 picture kemiller2002 · Jul 13, 2009

This:

function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById("btnAlelrt").click();

        }       

needs to be this:

function ConfirmTransfere() {
        if (confirm("Syatem not allow negative inventory, would you like to continue ?") == true) {
            document.getElementById('<%=btnAlert.ClientID%>').click();

        }     

The problem is that your button is an ASP.Net control and will generate it's own client id, which will be different from the ID you specified. putting in the code <%=btnAlert.ClientID%> Will post the generated one out to the browser.