selecting dom elements after html was inserted in a page with ajax

22,443

Solution 1

Use delegate event like on for version 1.7+

$('body').on('change', '#chapters-select', function(){
    alert('changed');
});

To increase performance instead of body you should write the closest static(Not added dynamic with ajax or javascript) element that holds "chapters-select

If you are using older version of jQuery choose the appropriate method with the following table:

$(selector).live(events, data, handler);                // jQuery 1.3+  
$(document).delegate(selector, events, data, handler);  // jQuery 1.4.3+  
$(document).on(events, selector, data, handler);        // jQuery 1.7+  

on docs:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Solution 2

Run this once, after the page's first load.

$("body").delegate('#chapters-select','change', function(){
    alert('changed');
});

It's equivalent to @gdoron's answer, but is compatible with versions of jQuery older than 1.7

Share:
22,443
Mythriel
Author by

Mythriel

Updated on July 25, 2021

Comments

  • Mythriel
    Mythriel almost 3 years

    I created an ajax tab navigation with html being inserted into the page. the code looks like this:

    $.ajax({
            type: 'POST',
            url: 'main/ajaxjson/load_course_details',
            data: {page : which, course_id: id},
            success: function(home){
    
                $('#ajax-content ').hide();
                $('#ajax-content').empty().append(home);
                $('#ajax-content').fadeIn(); 
            }
    
        });
    

    ok...so I append my markup into my html. Now I need to select dom elements from the inserted html, but I can not. I have the following code:

    <a href="javascript:;" class="light-button">Next</a>
    <select id="chapters-select">
        <?php foreach ($chapters as $chapter) : ?>
        <option value="<?php echo $chapter->id; ?>"><?php echo $chapter->title; ?></option>
        <?php endforeach; ?>
    </select>
    

    Here I generate the select options dynamically. When I try to do this:

    $('#chapters-select').change(function(){
        alert('changed');
    });
    

    it doesn't work. How can I use javascript after I append the html via ajax ?

  • Treffynnon
    Treffynnon about 12 years
    Or just rebind the event handler in the callback for $.ajax.
  • Mythriel
    Mythriel about 12 years
    thank you. it is working. i don't understand why it wasn't working before, but i will research it
  • gdoron is supporting Monica
    gdoron is supporting Monica about 12 years
    @Treffynnon. usually It's best practice to do things once and in one place only.
  • gdoron is supporting Monica
    gdoron is supporting Monica about 12 years
    @Mythriel. Read the docs I added and referenced, It should answer all your questions and thoughts.