0

I have a form like this:

<form>
  <div class="repeatable">
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three">
        <input name="inner_three">
        <a>+</a>
      </div>
      <input name="level_two">
      <a>+</a>
    </div>
    <input name="level_one">
    <a>+</a>
  </div>
</form>

The plus sign clones the entire repeatable closest to itself. I want a jQuery function to iterates through repeatables and make the input name's an array like this:

<form>
  <div class="repeatable">
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three[0][0]">
        <input name="inner_three[0][0]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[0][1]">
        <input name="inner_three[0][1]">
        <a>+</a>
      </div>
      <input name="level_two[0]">
      <a>+</a>
    </div>
    <div class="repeatable">
      <div class="repeatable">
        <input name="level_three[1][0]">
        <input name="inner_three[1][0]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[1][1]">
        <input name="inner_three[1][1]">
        <a>+</a>
      </div>
      <div class="repeatable">
        <input name="level_three[1][2]">
        <input name="inner_three[1][2]">
        <a>+</a>
      </div>
      <input name="level_two[1]">
      <a>+</a>
    </div>
    <input name="level_one">
    <a>+</a>
  </div>
</form>

We may have any number of repeatables. In the example there are 3 levels total. It may 1, 2, 3, 4 or any number.

Vahid
  • 3,384
  • 2
  • 35
  • 69

1 Answers1

0
$(function(){

  $('form > .repeatable').each(function(l1_Index, l1_elem){
      $('> .repeatable', l1_elem).each(function(l2_Index, l2_elem){
          $('> .repeatable', l2_elem).each(function(l3_Index, l3_elem){
              $('input', l3_elem).each(function(input_Index, input_elem){

                var computed = (input_Index === 0 ? 'level_three' : 'inner_three') + 
                      '[' + l1_Index + ']' + '[' + l2_Index + ']' ;

                $(input_elem).attr('name', computed);

              });
          });
      });
  });
});

see code example here https://jsbin.com/colocunoqo/edit?html,js,output

p.s. any templating lib like angular would make this super easy for you

EDIT: with recursion https://jsbin.com/sisivucaxe/edit?html,js,output

bresleveloper
  • 5,940
  • 3
  • 33
  • 47
  • Thank you for the solution. As I've said in the last sentence, the number of "repeatable"s is unknown. Could you please edit the post for unknown number of "repeatable"s? Thank you in advance. – Vahid Jul 20 '16 at 09:02
  • does the 2nd link helps you? – bresleveloper Jul 20 '16 at 12:22