Cannot find asp: text field in Javascript

I am trying to add the onkeydown attribute in asp: textbox. For some reason, my code cannot find the text box in the login window.

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>
+3
source share
3 answers

Your code is trying to add event handler attributes in the client script. This should happen in a server-side code block. Sort of:

<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 page, place an attribute.Add call in the PreRender event.

+1
source

aspx script, UserName Password KeyDownHandler:

<script runat="server">
   protected void Page_Load(object sender, EventArgs e)
   {
      TextBox userNameControl = FindControl("UserName") as TextBox;
      TextBox passwordControl = FindControl("Password") as TextBox;

      if (userNameControl != null)
         userNameControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)"); 

      if (passwordControl != null)
         passwordControl.Attributes.Add("onKeyDown", "KeyDownHandler(this)"); 
   }
</script>

script:

<script type="text/javascript">
function KeyDownHandler(domButton) 
{ 
    if (event.keyCode == 13) 
    { 
        event.returnValue=false;     
        event.cancel = true; 
        domButton.click(); 
    } 
} 
</script>
0

Try connecting an event handler parameter like this:

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

function KeyDownHandler(domButton)
{
    if (event.keyCode == 13)
    {
        event.returnValue=false;    
        event.cancel = true;
        domButton.click();
    }
}
</script>
-1
source

Source: https://habr.com/ru/post/1749203/


All Articles