Tags generated dynamically with ajax are not seen by jquery

1

I am generating a PivotTable via AJAX which in one of the TDS there is a link.

<a href="#modalInserirDescontoCB" class="modal-trigger id_aluno">104490</a>

The link should accomplish two tasks:

  • Open a modal containing a form (class modal-trigger of materializecss is responsible);
  • Fill in one of the form fields with the text of the clicked link.
  • The code for the second task:

    $('.id_aluno').click(function () {
        $('#campo_aluno').val(this.text);
    });
    

    Where #campo_aluno is input of modal.

    The AJAX requesting:

    tabela = $('#tabela-resultado-alunos');
    filtro = $('#aluno').val();
    
    if (filtro == '') {
        alert('Preencha o campo.');
        return false;
    }
    
    $.ajax({
        url: path + 'cb/lista-alunos',
        type: 'post',
        data: {
            get: filtro,
        },
        dataType: 'html',
        beforeSend: function () {
            tabela.html('Carregando...');
        },
        success: function (retorno) {
            tabela.remove('.bloco');
    
            // Atribui o retorno HTML para a div correspondente             
            if (retorno == 0) {
                $(tabela).html('Deu ruim');
            } else {
                $(tabela).html(retorno);
            }
        },
        error: function (erro, er) {                 
            $(tabela).html('Erro ' + erro.status + ' - ' + erro.statusText + '</br> Tipo: ' + er + '</p>');
        }
    });
    

    The PHP function that returns the HTML table:

    $output = <<<HTML
        <table class="striped bordered">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>NOME</th>
                    <th>CPF</th>
                </tr>
            </thead>
            <tbody>
    HTML;
    
    foreach ($alunos as $a) {
        $output .= <<<HTML
            <tr>
                <td><a href="#modalInserirDescontoCB" style="cursor: pointer" title="Preencher número de aluno com esse valor" class="modal-trigger id_aluno">{$a->pf_id}</a></td>
                <td>{$a->nome}</td>
                <td>{$a->cpf}</td>
            </tr>
    HTML;
    }
    
    $output .= '</tr></tbody></table>';
    
    return $output;
    

    When I click on one of the generated links, none of the functions are executed.  I also tried a simple $('.id_aluno').click(function(){console.log('funcionou')}); and nothing happens, as if the generated content was not seen by jquery .

        
    asked by anonymous 18.01.2017 / 18:42

    3 answers

    2

    You can use .on , successor of .delegate , since the element was added to the DOM after it was initially assembled and interpreted by the script. Try something like:

    $(document).on('click', '.id_aluno', function(){     
        $('#campo_aluno').val(this.text);
        $('#meuModal').openModal(); 
    }); 
    
        
    18.01.2017 / 18:56
    2

    Thiago, I believe the error is in

    $('.id_aluno').click(function () {
        $('#campo_aluno').val(this.text);
    });
    

    Because the event is bound to the element that is already created, and as you mentioned, other elements are created dynamically.

    The solution would be for you to link the event to jquery on.

    $(".id_aluno").on("click", function(){
        $('#campo_aluno').val(this.text);
    });
    
        
    18.01.2017 / 18:47
    1

    Change this section:

    $('.id_aluno').click(function () {
        $('#campo_aluno').val(this.text);
    });
    

    by this:

    $('.modal-trigger.id_aluno').click(function () {
        $('#campo_aluno').val(this.text);
    });
    
        
    18.01.2017 / 18:48