Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 564
BioXhazard Avatar asked Jul 23 '26 10:07

BioXhazard


1 Answers

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.

like image 56
David Avatar answered Jul 26 '26 01:07

David



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!