A LinkButton, DefaultButton, UpdatePanel and FireFox
What are we going to do today Brain? Today Pinky? We are going to TAKE OVER THE... learn to use the stuff in the title...
I recently did a post regarding An UpdatePanel, FireFox and the Default button. One thing that has stumped many ASP.NET Developers is... what about the @#%)&* Linkbutton! I can click it... but I WANT TO PRESS ENTER!
As more and more websites are becoming more visual appealing the "button" is getting it's due and is being chucked off of the 50th story window and smashing into all those ugly cars on the ground. So what can we use instead? An image button is great, but it has design issues that are hard to get out of.
A LinkButton is a great tool. It renderes as an anchor (<a ... />) tag, and you can add some funky CSS style to it. Later today I'll be updating my projects site with some examples on building some very COOL linkbutton's.
So, how do we get the link button to actually do something useful when someone presses enter?
So here we go. Let's start off with some script:
if(evt.which || evt.keyCode)
if((evt.which == 13) || (evt.keyCode == 13))
location = document.getElementById('<% =btnLogin.ClientID %>').href;
Key 13 is the Key code for the enter button. So whenever this function is called, and the KeyCode is 13 (my enter button), change the location of this document. Note that location is not a variable, changing that will redirect the browser.
We also need to return false. Why? Whenever a link button is activated through.. "enter" it will just refresh the form. Ohhh, just like the button in FireFox. Yes Pinky.. just like that. Remember that the <asp:linkButton /> gets rendered as an anchor tag... so what does the anchor tag NOT have? a Click event. Remember default buttons fire a click event, which is how they work - seeing an Anchor tag does not have this, this won't work. The form is just submited without the __EVENTTARGET parameter.
There is one solution that creates their own "click" event for the LinkButton. You can look at it here (this solution does work as well, i just found it too much). I wanted something simpler, Simple is key.
Ok back on track.
<asp:TextBox ID="txtUserName" runat="server" SkinID="DataEntryTextBox" onkeydown="keyPress(event);" />
So everytime someone presses a key in this box, it will fire our client side function.
And... that's it.
There are a few drawbacks to the solution I have presented.
- If you're page has multiple buttons / imagebuttons on it, without careful checking those buttons will be "invoked" before yours is. You will have to do a bit of extra scripting to make sure that doesn't happen.
- You have to add the onkeydown event listener to every textbox / text area.
And that's it. If you have any questions please let me know.