tags:

views:

347

answers:

1

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!

+1  A: 

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(.........
Clyde
I like the class idea, since the code is used in a widget I can't guarantee that there won't be other FRAMESETS on the page. Thanks!
Zachary
For bonus points, this would be a great experiment for learning to create jquery plugins. It would be a nice simple plugin, so that the code on the page would just be: $('select my fieldsets').UseAutoEnterKey();
Clyde
I'll give it a shot, it'll be a good excerise... I'll post what my results here... Zach
Zachary
I built a basic jQuery plug-in to assign the Enter Key to a Button. Here is a link to the post on my blog: http://www.zachhunter.net/blog/2009/05/30/AssignEnterKeyJQueryPlugIn.aspx
Zachary