Back to all posts

jQuery and Clicking an ASP.NET LinkButton

Posted on Jun 21, 2012

Posted in category:
Development
ASP.NET

As a web developer, one common request is to make sure that the interfaces we build out for users look the best that they can and also provide users with the best experience both via the keyboard and mouse.  As part of this we will often have areas of conflict.  This post is going to cover one common scenario that will impact users that might be using DotNetNuke common styles or working to create their own custom button styles.  With ASP.NET it is common for people to use "LinkButton" controls to trigger actions rather than your standard "Button" controls as they are easier to style.

There is nothing wrong with this until you try to perform actions against the 'LinkButton' and it doesn't function as you would expect.  For this purpose of this post lets say we are building a custom login form that has two textboxes; txtUsername and txtPassword and a single LinkButton btnLogin.  We want to ensure that if the user presses enter on either of the textboxes that they are logged in.

Using standard jQuery we would try something like this:

Non-Working Example
$("#<%=txtPassword.ClientID %>").keydown(function(event) {
    if (event.keyCode == 13) {
        $("#<%=btnLogin.ClientID %>").click();
    }
});

This is a pretty standard jQuery method to listen for the enter key and simply "click" the button.  However, if you are using a LinkButton this code will not work.  The reason for this is that a LinkButton is rendered to the browser as an Anchor tag with a href property that contains a javascript action to trigger the postback.  Click does nothing on the button as there is nothing for it to complete.

To get around this you need to actually look into the generated anchor tag, grab the href value and evaluate it.  Similar to the following:

Working Example
$("#<%=txtPassword.ClientID %>").keydown(function(event) {
    if (event.keyCode == 13) {
        eval($("#<%=btnLogin.ClientID %>").attr('href'));
    }
});

Using this structure the postback will be triggered and the user will be logged in as you expect them.  This works great for any linkbutton, including those styled with the default DotNetNuke 6.x form pattern styles.  Feel free to share you comments/feedback below.