1
var choices = [[]];
var i = 0;
$('.type_multiple-choices').each(function () {
   $('input[name^=choice]').each(function () {
      choices[i].push($(this).val());
   });

   i++;
});

I want to create multidimensional array and push input datas into it.

But when i try like this, error occures:

Cannot read property 'push' of undefined

1 Answer 1

3

The problem is because choices[i] doesn't exist yet. You instead need to push an array to choices.

Presumably you also want to restrict the [name^=choice] selection to only those within the current .type_multiple-choices element. For that you can use find() in combination with nested map() calls, like this:

var choices = $('.type_multiple-choices').map(function () {
  return [$(this).find('input[name^=choice]').map(function () {
    return $(this).val();
  }).get()];
}).get();

console.log(choices);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="type_multiple-choices">
  <input name="choice1" value="choice1" />
  <input name="choice1" value="choice2" />
  <input name="choice1" value="choice3" />
</div>
<div class="type_multiple-choices">
  <input name="choice1" value="choice4" />
  <input name="choice1" value="choice5" />
  <input name="choice1" value="choice6" />
</div>
<div class="type_multiple-choices">
  <input name="choice1" value="choice7" />
  <input name="choice1" value="choice8" />
  <input name="choice1" value="choice9" />
</div>

Sign up to request clarification or add additional context in comments.

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.