0

I've a form with input fields as follows:

<form "data-qustion_form"=true>
  <input name="question[description]" value="quesd">
  <input name="question[answers][0][description]" value="ansd1">
  <input name="question[answers][1][description]" value="ansd2">
</form>

I'm using https://github.com/marioizquierdo/jquery.serializeJSON to convert the form data to json. Also tried using https://stackoverflow.com/a/8407771/707636. Both works great. But the I'm not able to loop through the array in the json.

I've following js

$("[data-question_form]").on("submit", function(e) {
  var o = $(this).serializeObject();  // $(this).serializeJSON(); both results same
  console.log(o);
  console.log(o["question"]);
  console.log(o["question"]["answers"]);
  $.each(question["answers"], function() {
    console.log("print test");  // I don't see this on console in Chrome inspector
  }
  e.preventDefault();
}

The output on console in Chrome inspector is as follow:

Object {utf8: "✓", question: Object}
Object {description: "quesd", answers: Array[0]}
[1362289041238: Object, 1362289045644: Object]

Further expanding [1362289041238: Object, 1362289045644: Object] shows the length: 0.

How can I iterate through this array to read each answer description in jQuery?

Community
  • 1
  • 1
Bongs
  • 5,502
  • 4
  • 30
  • 50

2 Answers2

1

I wasn't able to find any problem with your code (see example), either using serializeObject - with the code in the linked answer - or using serializeJSON - with the code from GitHub. Your markup, however, had to be adjusted:

<form "data-qustion_form"=true>

to:

<form data-question_form="true">

P.S. as @jchapa pointed out, the question["answers"] was wrong too - and the parenthesis didn't balance. But I'm assuming it's just the code you pasted here, your actual code must be right (or you wouldn't get any results at all).

  $.each(o["question"]["answers"], function() {
    console.log("print test");  // I don't see this on console in Chrome inspector
  });
});
mgibsonbr
  • 21,755
  • 7
  • 70
  • 112
0

Okay, I just solved it but making a small change in the name attribute of input elements. Added [] before the counter as follows:

<input name="question[answers][][0][description]" value="ansd1">
<input name="question[answers][][1][description]" value="ansd2">

Now I'm able to loop through it :)

Bongs
  • 5,502
  • 4
  • 30
  • 50