Zachary
Zachary

Reputation: 6532

Change Enter Key using jQuery?

I use mutliple framesets on a page, and each frameset has an associated button to perform a server/client side postback. I wanted to change the default enter key to select the correct button and this was my soltuion using jQuery.

    $("#<%= SearchCustomers.ClientID %>").find(":input").click(function() { $(this).parents("FIELDSET").addClass("default"); }).blur(function() { $(this).parents("FIELDSET").removeClass("default"); });
    $("#<%= SearchGroups.ClientID %>").find(":input").click(function() { $(this).parents("FIELDSET").addClass("default"); }).blur(function() { $(this).parents("FIELDSET").removeClass("default"); });


    $(document).keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            $(".default").find(":submit,:button").click();
            return false;
        }
    });

This is working perfect, but I was looking for ways to improve this. Right now, the code is dependent on me setting the framesets to "runat=server" so I can access the "ClientID" property and inject the ID into my javascript. This makes the code a little less re-usable, so I was curious if somebody else had a better idea...

Thanks for your comments!

Upvotes: 0

Views: 847

Answers (1)

Clyde
Clyde

Reputation: 8145

Since your first two lines are so similar I'd reduce it to:

$('FIELDSET').find(":input").click(function() {
  $(this).parents("FIELDSET").addClass("default"); }).blur(function() {
  $(this).parents("FIELDSET").removeClass("default"); });

If there aren't any other framesets on the page than the two you care about, this should be fine. Then you don't need to have the ClientID.

If you can't guarantee those are the only two on the page, then I think you do need the runat=server and ClientID -- because you do in fact need to uniquely identify those particular two framesets

EDIT: Alternatively, you could mark fieldsets that you want to have exhibit this behavior with a particular class:

<fieldset class='UseAutoEnterKey'> ....

Then you can add the behavior all in one with the class selector:

$('FIELDSET.UseAutoEnterKey').find(.........

Upvotes: 1

Related Questions