jQuery cannot find elements added via append

Asked

Viewed 36 times

0

I have the following request that lists the students in a table:

jQuery('#presencaExibir').click(function(e){
    e.preventDefault();
    $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
       }
   });
   jQuery.ajax({
     url: "/presenca/alunos",
     method: 'post',
     data: {
        sala: jQuery('#sala').val(),
        horario: jQuery('#dia-horario').val()
     },
     success: function(result){
        $('#diaChamada').text($('#dia-semana option:selected').text());

        $('#listaAlunos').text('');

        $.each(result.alunos, function(k, aluno){
            $('#listaAlunos').append(
                "<tr>" +
                    "<div class='row'>" +
                        "<td class='id-aluno'>" + aluno.ID_Aluno + "</td>" +
                        "<td class='col-6'>" + aluno.Nome + "</td>" +
                        "<td><i class='material-icons presenca presente'> account_circle </i></td>" +
                    "</div>" +
                "</tr>"
            );
        });
     }});
});

What I need to do is take all values in the "id-student" class td via jQuery and send in another ajax request:

jQuery('#finalizarBtn').click(function(e){
    e.preventDefault();
    $.ajaxSetup({
       headers: {
           'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
       }
   });
   jQuery.ajax({
     url: "/presenca/finalizar-dia",
     method: 'post',
     data: {
        alunos: $('.id-aluno').text()
     },
     success: function(result){
        console.log(result.alunos);
     }});
});

However, when I try to do this, the result I have of $('.id-aluno').text() is

Undefined

How can I get these values inserted in the table dynamically?

  • If you have several elements with the class id-aluno your search $('.id-aluno') will return a list of elements, which does not have the method text.

  • @Anderson, all jQuery queries return a list, even if you look for a single element. The method .text() returns the innerText of the first element of this list. @Antony, could add your HTML and the return of Ajax to your question, so that it becomes testable?

  • @user140828 Not so. The $('.id-aluno').text() will return the text of all elements with the class .id-aluno, not just the first.

  • 1

    Antony, I think you’re making a mistake. The $('.id-aluno').text() will never resume undefined, even if there is no element with that class.

  • @Sam thanks for watching me. In fact I was confusing things myself and Undefined was coming from a wrong treatment I was doing within PHP. I managed to settle here.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.