lloydphillips
lloydphillips

Reputation: 2855

How to do a jquery find on intially hidden element

I have a div with a class name 'form'. When the page is initially loaded this div is hidden (it's an asp.net web forms Panel control). The panel is displayed when a search button is clicked to open a search form on the page. I need to capture when the user hits enter in any of the textboxes and have it click the Search button which I've added a class named 'form-default'.

The problem I have is that my event handler isn't hooked up because because 'form' wasn't visible when the page was initially loaded and so couldn't access my textboxes. I could have them attach when the form is opened but I'm trying to get a small code snippet that can be loaded in a global file so that we can easily alot class names of 'form' to div's and 'default-form' to buttons within the div to have default buttons within the page in more than one place. I don't want developers to need to remember to hook up the calls when the UI changes. Can I use live() to hook this up or am I doing something else wrong?

$(".form").find(".ec-text").keydown(function(e){
if (e.which == $.ui.keyCode.ENTER){
this.closest(".form-default").click();
}
}); 

EDIT: This works fine:

$(".ec-text").live("keydown", function(e){
    if (e.which == $.ui.keyCode.ENTER){
        this.closest(".form-default").click();
    }
});

BUT I need to attach the event handler to items ONLY inside a .form div. Applying this:

$(".form").find(".ec-text").live("keydown", function(e){
        if (e.which == $.ui.keyCode.ENTER){
            this.closest(".form-default").click();
        }
    });

doesn't work. Any ideas?

Upvotes: 2

Views: 249

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156748

The easiest thing would be to change your live binding code so that it will bind only to items that are inside the form. (Your code didn't work because the .find sort of breaks the way that live handlers work.)

$(".form .ec-text").live("keydown", function(e){
    if (e.which == $.ui.keyCode.ENTER){
        this.closest(".form-default").click();
    }
});

Upvotes: 2

Related Questions