I have a asp Image Button that needs to be clicked via a Javascript function. The keypress of a textbox should fire this image buttons server side event as well upon hitting the enter key. The code is as follows: -
Markup
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="images/butt_searchoff.png"
class="sb_search" ToolTip="Search the Database" AlternateText="Search" OnClick="ImageButton3_Click" OnClientClick="SetExpandedCount()"/>
<input id="tbSearch" runat="server" class="sb_input" type="text" autocomplete="off" onkeypress="return OverridePostBackOnEnter(event, '" & ImageButton3.ClientID & "');" />
I want to pass the ImageButton3 ClientId as a param to a Javascript function called OverridePostBackOnEnter.
The Javascript looks like this:
function OverridePostBackOnEnter(event, ctrl) {
if (event.keyCode == 13) {
alert(ctrl);
if ($.browser.mozilla) {
__doPostBack(ctrl, 'OnClick'); //for IE
}
else {
//but for other browsers you should use
__doPostBack(ctrl, 'OnClick');
}
}
};
What I'm finding is a) I can't get the correct ClientId to be passed, I just get either undefined or null.
and b) if I hard code and change the ctrl to 'cmain_ctl00_ImageButton3' the __dopostback is not invoking my server-side code for the ImageButton3.
Any help on this would be greatly appreciated.
Edit
Ok think I have found a solution for this and thought I should update the post in case anyone needs it.
Firstly I have set the 'ClientIdMode' on ImageButton3 to 'Static'
<asp:ImageButton ID="ImageButton3" ClientIDMode="Static" runat="server" ImageUrl="images/butt_searchoff.png" class="sb_search" ToolTip="Search the Database" AlternateText="Search" OnClick="ImageButton3_Click" OnClientClick="SetExpandedCount()"/>
this allows me to pass the id of the button to the function 'OverridePostBackOnEnter'
<input id="tbSearch" runat="server" class="sb_input" type="text" autocomplete="off" onkeypress="return OverridePostBackOnEnter(event, 'ImageButton3');" />
Then my Javascript becomes:
function OverridePostBackOnEnter(event, ctrl) {
if (event.keyCode == 13) {
if ($.browser.mozilla) {
var overridctrl = document.getElementById(ctrl);
__doPostBack(overridctrl.name, ''); //for IE
}
else {
//but for other browsers you should use
var overridctrl = document.getElementById(ctrl);
__doPostBack(overridectrl.name, '');
}
}
};
By looking into 'yourForm._EVENTTARGET.value' and 'yourForm._EVENTARGUMENT.value' I could see those values were not being set. By using 'document.getelementId' and passing the 'control.name' sets those values and enables the '__dopostpack' to invoke the serverside event.