jQuery: Generate "name" Attribute Array Dynamically

159 Views Asked by At

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.

1

There are 1 best solutions below

2
bresleveloper On
$(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