Search code examples
javascripttextboxenteronkeydown

Can't find asp:textbox in Javascript


I am trying to add the onkeydown attribute to an asp:textbox. For some reason my code can't find the textbox that is inside a loginview.

Am I doing something wrong?

<script type="text/javascript">
window.onload = function() {
    UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
    Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')");
}

function KeyDownHandler(btn)
{
    if (event.keyCode == 13)
    {
        event.returnValue=false;    
        event.cancel = true;
        document.getElementById(btn).click();
    }
}
</script>

Solution

  • Your code is trying to add the event handler attributes in the client script. This needs to happen in a server-side code block. Something like:

    <script runat="server"> 
        UserName.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')"); 
        Password.Attributes.Add("onKeyDown", "KeyDownHandler('" + btn.ClientID + "')"); 
    </script>
    <script type="text/javascript">
    function KeyDownHandler(btn) 
    { 
        if (event.keyCode == 13) 
        { 
            event.returnValue=false;     
            event.cancel = true; 
            document.getElementById(btn).click(); 
        } 
    } 
    </script> 
    

    Alternatively, if you have a code-behind page, put the attribute.Add calls in the PreRender event.