Add fields to form dynamically with ajax and retrieve values I am trying to add a combination of text field and a select box to a form dynamically using Drupal 7 Ajax, when i click on a button.

But i have 2 issues here:


I am not able to add more than 1 set of fields in the form with Ajax
After i submit the form, i am not able to retrieve the values of the form. They are empty. I have the fields as "name_1", "select_1", "name_2", "select_2", etc.


I want to know if there is any way to solve it, with / without using a fieldset.

My custom module code:

function my_form_form($form, &amp;$form_state, $no_js_use = FALSE) {  
  $form['#tree'] = TRUE;
  $form['add_more'] = array(
    '#type' =&gt; 'button',
    '#value' =&gt; t('Add More'),
    '#href' =&gt; '',
    '#ajax' =&gt; array(
    'callback' =&gt; 'ajax_simplest_callback',
    'wrapper' =&gt; 'names-fieldset-wrapper',
  );
  $form['names']['name_1'] = array(
    '#type' =&gt; 'textfield', 
    '#title' =&gt; t('Name 1'),  
    '#attributes'=&gt;array('id'=&gt;'name_1', 'name'=&gt;'name_1'),           
  );
  $form['names']['select_1'] = array(
    '#type' =&gt; 'select', 
    '#title' =&gt; t('Select 1'),    
    '#attributes'=&gt;array('id'=&gt;'select_1', 'name'=&gt;'select_1'), 
    '#options'=&gt;array('1'=&gt;'One', '2'=&gt;'Two', '3'=&gt;'Three'),
  );
  $form['submit'] = array(
    '#type' =&gt; 'submit',
    '#value' =&gt; t('Submit'),  
  );
  $form['#submit'][] = 'my_form_add_more_submit';       
  return $form;
}
function ajax_simplest_callback($form, &amp;$form_state) {
  if (empty($form_state['num_names'])) {
    $form_state['num_names'] = 1;
  }
  else {
    $form_state['num_names']++;
    $form_state['rebuild'] = TRUE;
  }

  for ($i = 1; $i &lt; $form_state['num_names']; $i++) {       
    $form['names']['name_'.$i+1] = array(
      '#type' =&gt; 'textfield', 
      '#title' =&gt; t('Name '.$i+1),    
      '#attributes'=&gt;array('id'=&gt;'name_'.$i+1, 'name'=&gt;'name_'.$i+1), 
    );    
    $form['names']['select_'.$i+1] = array(
      '#type' =&gt; 'select', 
      '#title' =&gt; t('Select '.$i+1),    
      '#attributes'=&gt;array('id'=&gt;'select_'.$i+1, 'name'=&gt;'select_'.$i+1), 
      '#options'=&gt;array('1'=&gt;'One', '2'=&gt;'Two', '3'=&gt;'Three'),
    );
  }
  return $form['names'];
}

function my_form_add_more_submit($form, &amp;$form_state) {
  print_r($form_state['values']);
  exit();
}
Dont set any field #required to true.

 $form['markup'] = array(
        '#type' =&gt; 'markup',
        '#prefix' =&gt; '&lt;div id="my-wrapper"&gt;',
        '#suffix' =&gt; '&lt;/div&gt;',
    );
 $form['markup']['myfield'] = array(
        '#type' =&gt; 'textfield', 
        '#size' =&gt; 12,
    );