开发者

Can't find asp:textbox in Javascript

开发者 https://www.devze.com 2023-01-03 01:29 出处:网络
I am trying to add the onkeydown attribute to an asp:textbox. For some reason my code can\'t find the 开发者_Go百科textbox that is inside a loginview.

I am trying to add the onkeydown attribute to an asp:textbox. For some reason my code can't find the 开发者_Go百科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>


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.


In your aspx file, add the server script that will bind existing UserName and Password textboxes to a client event handler called 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>

Then declare the event handler's client script:

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


Try wiring the event handler parameter this way:

<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>
0

精彩评论

暂无评论...
验证码 换一张
取 消