tags:

views:

180

answers:

1

I have a few selects that I have built as external components in a php page and then load into an html page. For example, I'm likely to use the component "usersList" in several places throughout the site, so my php generates this list and then I use load in jquery to call the component, like this:

$("#samaritan").load('usersList.php');

That works beautifully, and I'm able to write jquery in the containing document to get the val() of my usersList just fine. I want to be able to cause things to happen onChange of this list. The only problem is that the change event seems to only want to fire when the jquery code is on the same page as the original component. For example, the following code will fire an alert with the value of the drop-down when I change the select only when this code is on the php page that generates the select.

$("select").change(function() {
                alert("you chose "+$(this).val());
            });

I'd rather not have to write this code straight onto the component page b/c I'd like the behavior to be different in the different places I use it. I've tried using .blur, but I get the same result. Any ideas how to trigger a change event on a select from the document containing a select that is loaded into a div?

+2  A: 

Sounds like you are running the code to add the handler before the element is actually added to the DOM. Make sure that your jQuery code adding the handler is executed after the load function completes its work. When you reload the list, you'll need to reapply the handler. The easiest way to do this is to apply the handler in the load method callback. Unfortunately you can't use the live handlers as they don't support the change event.

$("#samaritan").load('usersList.php', function() {
    $("select").change(function() {
        alert("you chose "+$(this).val());
    });
});
tvanfosson
why is it that the right answer can be so simple? (actually, I'm glad it's not more complex than this). This worked beautifully, and taught me something about the order of creation.
staypuffinpc