Nevermore
Nevermore

Reputation: 1743

Create and push to a multidimensional array

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

Upvotes: 1

Views: 375

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

Upvotes: 3

Related Questions