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?

2
  • $.each(question["answers"], function() { looks wrong to me. Commented Mar 3, 2013 at 5:57
  • I did also try $.each(question["answers"], function(k,v) { console.log(v); }, didn't work. Commented Mar 3, 2013 at 5:58

2 Answers 2

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
  });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer - pushed you to 10k ;)
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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.