This is a migrated thread and some comments may be shown as answers.

[Solved] var Button1 = $find("<%= SearchButton.ClientID %>");

3 Answers 86 Views
General Discussions
This is a migrated thread and some comments may be shown as answers.
Casey
Top achievements
Rank 1
Casey asked on 23 Jul 2009, 02:15 PM
Hello,

In my page there is a text box where user's can search for different organizations in the company. I want them to be able to hit enter and have the SearchButton's onclick event to be fired. Currently when they hit enter, the first button in the code has its onclick event fired, which is not what I want to happen.

When I enter text into the textbox and press enter, the page fails with a javascript error: "Microsoft JScript runtime error: 'null' is null or not an object", and the following code is highlighted: Button1.click(); Also, when I hover over Button1, the little window that displays the value shows null. I'm not sure why this control is null. Any ideas on what could be causing this behavior would be appreciated.

Here is the code I am using to make this happen:

protected void Page_Load(object sender, EventArgs e)  
    {  
        this.TextBox1.Attributes.Add("onkeypress","button_click()");  
    } 

function button_click() {  
                     if (window.event.keyCode == 13) {  
                         var Button1 = $find("<%= Button1.ClientID %>");  
                         Button1.click();  
                         window.event.cancel = true;  
                     }  
                 } 

<asp:Button ID="Button1" runat="server"   
                Text="Search" Width="70px" onclick="Button1_Click" /> 

3 Answers, 1 is accepted

Sort by
0
Casey
Top achievements
Rank 1
answered on 23 Jul 2009, 03:38 PM
As a workaround I placed the text box and button inside of a panel and set the panel's DefaultButton property equal to the button I wanted to be clicked when the Enter key was pressed. This will only work when the users are actually in the panel though.
0
Princy
Top achievements
Rank 2
answered on 24 Jul 2009, 05:55 AM
Hello Casey,

To access a normal asp button on the client you can use document.getElementById() or $get() method, since $find works mainly with AJAX controls. So this is how your java script should look like:
js:
function button_click() 
     {   
         if (window.event.keyCode == 13) 
          {   
             var btn = document.getElementById("Button1");   
             btn.click();   
             window.event.cancel = true;   
          }   
     }  

Thanks
Princy.
0
Casey
Top achievements
Rank 1
answered on 24 Jul 2009, 11:19 AM
Hey Princy,

Thanks for the reply. I have tried to use document.getElementById(), but I still received the javascript error. I'm not sure why it is returning null. 

Thanks,
Casey 
Tags
General Discussions
Asked by
Casey
Top achievements
Rank 1
Answers by
Casey
Top achievements
Rank 1
Princy
Top achievements
Rank 2
Share this question
or