Error with jquery array syntax

Asked

Viewed 31 times

0

I didn’t put all the code to not pollute the text and the doubt is about the syntax below:

I have 2 table html (tblPerguntas e tblRespostas) e preciso percorrer estas duas Tables e enviar para a Controller via Ajax;

   var iP = 0;
    var iR = 0;
    var tblPerguntas = $("#tblPerguntas > tbody");
    var tblRespostas = $("#tblRespostas > tbody");

    var Questionario = {
        "Id_Questionario": 1,
        "Nome_Questionario": "Pesquisa Domicilio",
        "Perguntas": []
    };

    tblPerguntas.find("tr").each(function () {
        Questionario.Perguntas.push({
            "Id_Pergunta": 1,
            "Id_Questionario": 1,
            "Pergunta": "Você tem TV a cores?",
            "Respostas": []
        });        
    });

    tblRespostas.find("tr").each(function () {
        Questionario.Perguntas.Respostas.push({
            "Id_Resposta": 1,
            "Resposta": "Sim Tenho 1 geladeira"
        });
    });

The question is about the push.

This error occurs: Uncaught TypeError: Cannot read property 'push' of undefined.

I believe syntax is wrong, if the syntax is the correct form ?

  • You defined Questionario.Perguntas as a array, then he does not possess the attribute Respostas. What has this attribute are the values of Questionario.Perguntas, that could be accessed by the index, Questionario.Perguntas[0].Respostas

  • Thank you @Andersoncarloswoss ! Would that be ?: var index = 0; tblResposts.find("tr"). each(Function() { Quiz.Questions[index].Respostas.Id_answer = 1, Quiz.Questions[index].Respostas.Answer = "Yes I have 1 refrigerator"; index++; });var index = 0; tblRespotures.find("tr"). each(Function() { Quiz.Questions[index].Respostas.Id_answer = 1, Quiz.Questions[index].Respostas.Answer = "Yes I have 1 refrigerator"; index++; });` , nothing happened.

1 answer

3


Take the first argument from the function of .each, which returns the index based on 0, place between brackets after Perguntas of the second .each:

tblRespostas.find("tr").each(function (i) {
  Questionario.Perguntas[i].Respostas.push({
      "Id_Resposta": 1,
      "Resposta": "Sim Tenho 1 geladeira"
  });
});

Note that the first argument of the function, represented by the variable i, returns the indexes of each tr table.

Browser other questions tagged

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