Вопрос

I am new to JavaScript.

I have this jQuery/AJAX code to refresh data (select, table) in a page:

$(document).ready(function () {
    $sport.change(function(){
        var $form = $(this).closest('form');
        var data = {};
        data['sport_id'] = $sport.val();       

        $.ajax({
            type: $form.attr('method'),
            data: data,
            url: Routing.generate('pphb_championnat_liste'),
            success: function(html){
                 
                $('#pphb_sportscoringbundle_findligue_ligue').replaceWith(                     
                    $(html).find('#pphb_sportscoringbundle_findligue_ligue')
                );
                $('#champTable').replaceWith(
                    $(html).find('#champTable')                    
                );
               
                $('#pphb_sportscoringbundle_findligue_ligue').change(function(){
                    var $form = $(this).closest('form');
                    var data = {};
                    data['ligue_id'] = $(this).val();      
                    
                    $.ajax({
                        type: $form.attr('method'),
                        data: data,
                        url: Routing.generate('pphb_championnat_liste'),
                        success: function(html){                   
                            $('#champTable').replaceWith(
                                $(html).find('#champTable')                    
                            );
                        }
                    });
                });
            }
        });       
    });
}); 

It work fine: populating "ligue select" when I'm changing "sport select" and refresh the table data, refresh the table data when I'm changing "ligue select".

But I have to put

$('#pphb_sportscoringbundle_findligue_ligue').change{ ...}

in the ajax success response. I would like to know how to write it properly.

Это было полезно?

Решение

you should use event delegation for dynamically created objects,

$(document).on("change", "#pphb_sportscoringbundle_findligue_ligue", function () {

 });

Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top