views:

43

answers:

2
+1  Q: 

jquery ajax help

I working with some ajax at the moment, the result of a successful ajax result is that some more content is add to the page on the fly. My problem is that is added on the fly it looks like I cannot attach any events to the elements that are added.

The flow of what happens is that the user selects an option from a dropdown list, the value of that selection is sent to a php function which then returns some more HTML to the page which is appended to a div on the page.

I know there is a problem with the elements not existing on domReady as I run a length() check and it confirms they dont 'exist' on the page.

Is there away around this so that I can run click event on the HTML that gets added after the first ajax request has returned successfully.

$(document).ready(function() {

//customise the select menus
$('#customselector').SelectCustomizer();;

$('.career_select .selectitems').click(function(){
    var selectedCareer = $(this).attr('title');
    $.ajax({
        type: 'POST',
        url: '/roadmap/step_two',
        data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
        success: function(html){
            $('.hfeed').append(html);
            $('#grade_choice').SelectCustomizer();
          }
    });
});

$('#grade_choice_options .selectitems').click(function(){
    var selectedGrade = $('#grade_choice_customselect').val();
    alert(selectedGrade);
})

});

+4  A: 

Use live() instead of click() directly:

$('.career_select .selectitems').live('click', function() { ....

live() essentially wires up any new elements that match that are added subsequently.

DavidGouge
A: 

Try using this plugin :

http://brandonaaron.net/code/livequery/docs : Live Query utilizes the power of jQuery selectors by binding events or firing callbacks for matched elements auto-magically, even after the page has been loaded and the DOM updated.

Nassif Bourguig
There are important differences between what jQuery 1.4 "live()" does and what "livequery" does. In this particular case, the "live()" facility in plain old jQuery would suffice and in fact be much preferable.
Pointy