title: JS - jQuery Dynamic add remove Input Fields
body: <p>I have a form where I add Input fields ( groups ) dynamically.</p>
  
  <p>It is quite a complex form, and a PART can be seen here : <a href="http://jsfiddle.net/obmerk99/y8JFb/1/" rel="nofollow">FIDDLE</a></p>
  
  <p>The actual error i get on the consul is :</p>
  
  <pre><code>Error: uncaught exception: query function not defined for Select2 s2id_autogen1
  </code></pre>
  
  <p>When I have fields already in the form ( the first two for example ) the <code>EDIT</code> and <code>REMOVE</code> button will work just fine .</p>
  
  <p>My problem is that the <code>REMOVE</code> button ( styled input field ) is not working for the dynamically <code>ADDED</code> fields ( actually "appended" by JS and populated from PHP )</p>
  
  <p><strong>NOTE on code:</strong> I know the code is a mess :-(. It was inherited and will be cleaned soon.</p>
  
  <p>it was copied and pasted from the HTML output.</p>
  
  <p>The <strong>ADD</strong> , <strong>REMOVE</strong> and <strong>EDIT</strong> are actually styled like buttons ( too long and irrelevant to paste ) </p>
  
  <p>The actual source is PHP and it is spanning over multiple files ( so is the JS ) , and thus a bit too complicated to show here .</p>
  
  <p>UPDATE : The code as per popular request :-)</p>
  
  <pre><code>  public function show_field_repeater( $field, $meta ) {
      global $post;  
      // Get Plugin Path
      $plugin_path = $this-&gt;SelfPath;
      $this-&gt;show_field_begin( $field, $meta );
      $class = '';
        if ($field['sortable'])  
          $class = " repeater-sortable";
      echo "&lt;div class='at-repeat".$class."' id='{$field['id']}'&gt;";
  
      $c = 0;
  
      $meta = get_post_meta($post-&gt;ID,$field['id'],true);
  
  
        if (count($meta) &gt; 0 &amp;&amp; is_array($meta) ){
           foreach ($meta as $me){
             //for labling toggles
             $mmm =  isset($me[$field['fields'][0]['id']])? $me[$field['fields'][0]['id']]: "";
             echo '&lt;div class="at-repater-block at-repater-block-'.$c.$field['id'].'"&gt;&lt;h3&gt;'.$mmm.' 
               &lt;span class="at-re-remove"&gt;
               &lt;input id="remove-'.$c.$field['id'].'" class="buttom button-primary" type="submitkb" value="Remove '.$field['name'].'" accesskey="x" name="removek"&gt;
              &lt;/span&gt;';
  
  
               echo '&lt;script&gt;
          jQuery(document).ready(function() {
                jQuery("#remove-'.$c.$field['id'].'").on(\'click\', function() {
                       var answer = confirm("Are you sure you want to delete this field ??")     
                     if(!answer){
                        event.preventDefault();    
                     }
  
  
                    jQuery(".at-repater-block-'.$c.$field['id'].'").remove();
  
                });
            });
          &lt;/script&gt;';  
  
             echo '&lt;span class="at-re-toggle"&gt;
             &lt;input id="edit-'.$field['id'].'" class="buttom button-primary" type="" value="Edit '.$field['name'].'" accesskey="p" name="editk"&gt;&lt;/h3&gt;
             &lt;/span&gt;
  
            &lt;span style="display: none;"&gt;
  
             &lt;table class="repeate-box wp-list-table widefat fixed posts" &gt;';
             if ($field['inline']){
               echo '&lt;tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top"&gt;';
             }
          foreach ($field['fields'] as $f){
            //reset var $id for repeater
            $id = '';
            $id = $field['id'].'['.$c.']['.$f['id'].']';
            $m = isset($me[$f['id']]) ? $me[$f['id']]: '';
            $m = ( $m !== '' ) ? $m : $f['std'];
            if ('image' != $f['type'] &amp;&amp; $f['type'] != 'repeater')
              $m = is_array( $m) ? array_map( 'esc_attr', $m ) : esc_attr( $m);
            //set new id for field in array format
            $f['id'] = $id;
            if (!$field['inline']){
              echo '&lt;tr&gt;';
            } 
            call_user_func ( array( &amp;$this, 'show_field_' . $f['type'] ), $f, $m);
            if (!$field['inline']){
              echo '&lt;/tr&gt;';
            } 
          }
          if ($field['inline']){  
            echo '&lt;/tr&gt;';
          }
          echo '&lt;/table&gt;&lt;/span&gt;
          &lt;span class="at-re-toggle"&gt;&lt;img src="';
             if ($this-&gt;_Local_images){
               echo $plugin_path.'/images/edit.png';
             }else{
               echo 'http://i.imgur.com/ka0E2.png';
             }
             echo '" alt="Edit" title="Edit"/&gt;&lt;/span&gt; 
          &lt;img src="';
          if ($this-&gt;_Local_images){
            echo $plugin_path.'/images/remove.png';
          }else{
            echo 'http://i.imgur.com/g8Duj.png';
          }
          echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'"&gt;&lt;/div&gt;';
          $c = $c + 1;
  
          }
        }
  
      echo '&lt;img src="';
      if ($this-&gt;_Local_images){
        echo $plugin_path.'/images/add.png';
      }else{
        echo 'http://i.imgur.com/w5Tuc.png';
      }
      echo '" alt="'.__('Add','mmb').'" title="'.__('Add','mmb').'" &gt;&lt;br/&gt;&lt;input id="add-'.$field['id'].'" class="buttom button-primary" type="submitk" value="Add '.$field['name'].'" accesskey="q" name="addk"&gt;&lt;/div&gt;';
  
      //create all fields once more for js function and catch with object buffer
      ob_start();
  
  
      echo '&lt;div class="at-repater-block"&gt;';
  
  
       echo '&lt;table class="wp-list-table repeater-table"&gt;';
  
  
      if ($field['inline']){
        echo '&lt;tr class="post-1 type-post status-publish format-standard hentry category-uncategorized alternate iedit author-self" VALIGN="top"&gt;';
      } 
  
      foreach ($field['fields'] as $f){
        //reset var $id for repeater
        $id = '';
        $id = $field['id'].'[CurrentCounter]['.$f['id'].']';
        $f['id'] = $id; 
  
        if (!$field['inline']){
          echo '&lt;tr&gt;';
        }
  
        if ($f['type'] != 'wysiwyg')
          call_user_func ( array( &amp;$this, 'show_field_' . $f['type'] ), $f, '');
        else
          call_user_func ( array( &amp;$this, 'show_field_' . $f['type'] ), $f, '',true);
        if (!$field['inline']){
          echo '&lt;/tr&gt;';
        }  
      }
       $js_code2 ='&lt;span class=\"at-re-remove\"&gt;&lt;input id="remove-'.$c.$field['id'].'" class="buttom button-primary remove-'.$c.$field['id'].'" type="submi7" value="Removevv " accesskey="7" name="remove7"&gt;&lt;/span&gt;';
      if ($field['inline']){
        echo '&lt;/tr&gt;';
      } 
  
  
  
       $js_code2 = str_replace("\n","",$js_code2);
       $js_code2 = str_replace("\r","",$js_code2);
      $js_code2 = str_replace("'","\"",$js_code2);
      echo $js_code2;
      echo '&lt;/table&gt;&lt;img src="';
      if ($this-&gt;_Local_images){
        echo $plugin_path.'/images/remove.png';
      }else{
        echo 'http://i.imgur.com/g8Duj.png';
      }
      echo '" alt="'.__('Remove','mmb').'" title="'.__('Remove','mmb').'" &gt;&lt;/div&gt;';
      $counter = 'countadd_'.$field['id'];
      $js_code = ob_get_clean ();
      $js_code = str_replace("\n","",$js_code);
      $js_code = str_replace("\r","",$js_code);
      $js_code = str_replace("'","\"",$js_code);
      $js_code = str_replace("CurrentCounter","' + ".$counter." + '",$js_code);
  
    echo '&lt;script&gt;
          jQuery(document).ready(function() {
            var '.$counter.' = '.$c.';
            jQuery("#add-'.$field['id'].'").on(\'click\', function() {
              '.$counter.' = '.$counter.' + 1;
              jQuery(this).before(\''.$js_code.'\'); 
               // jQuery("#'.$field['id'].'").append(\''.$js_code2.'\'); 
               // alert(\''.$js_code2.'\');
              update_repeater_fields();
            });
  
            });
          &lt;/script&gt;';  
          echo '&lt;script&gt;
          jQuery(document).ready(function() {
  
                jQuery(".remove-'.$c.$field['id'].'").on(\'click\', function() {
                       var answer = confirm("Are you sure you want to delete this field ??")     
                     if(!answer){
                        event.preventDefault();    
                     }
                    jQuery(".remove-'.$c.$field['id'].'").remove(); 
                });
            });
          &lt;/script&gt;';  
      echo '&lt;br/&gt;&lt;style&gt;
  .at-inline{line-height: 1 !important;}
  .at-inline .at-field{border: 0px !important;}
  .at-inline .at-label{margin: 0 0 1px !important;}
  .at-inline .at-text{width: 70px;}
  .at-inline .at-textarea{width: 100px; height: 75px;}
  .at-repater-block{background-color: #FFFFFF;border: 1px solid;margin: 2px;}
  &lt;/style&gt;';
      $this-&gt;show_field_end($field, $meta);
    }
  </code></pre>