How to add field to fieldset by ajax? I have a fieldset with one field by default. I want to add new fields by ajax (button "new item"). I can do it for usual field, but I have a problem with fieldsets.
How to do that?

For usual fields I do it like below:

$form['add_item'] = array(
    '#type' =&gt; 'button',
    '#value' =&gt; t('Add item'),
    '#ajax' =&gt; array(
        'wrapper' =&gt; 'content',
        'callback' =&gt; 'add_more_ajax',
        'method' =&gt; 'append',
        'affect' =&gt; 'fade',
    ),
);

function add_more_ajax($form, &amp;$form_state) {
    $form['image'] = array(
        '#title' =&gt; t('Image'),
        '#type' =&gt; 'managed_file',
        '#default_value' =&gt; '',
        '#upload_location' =&gt; 'public://images/',
    );
    return $form['image'];
}
First - ajax callback should not make any persistent changes to $form. It's only duty is to return proper part of form array. Render all elements in form creation function:

mymodule_form($form, &amp;$form_state) {
  $form['image'] = array (
    '#type' =&gt; 'fieldset',
    '#title' =&gt; t('images'),
    '#collapsible' =&gt; TRUE,
    '#collapsed' =&gt; FALSE,
    '#prefix' =&gt; '&lt;div id="product_images"&gt;',
    '#suffix' =&gt; '&lt;/div&gt;',
  );
  if (empty($form_state['image']['count'])) {
    // Keep number of fields either in form or form state, both works.
    $form_state['image']['count'] = 4; // Default number of elements
  }
  elseif( isset($form_state['triggering_element']) 
      and $form_state['triggering_element']['#machine_name'] == 'more_images_button' ) {
    // If form was triggered by proper form element, increase counter
    $form_state['image']['count']++;
  }
  // Loop to create elements
  for ($i = 0; $i &lt; $form_state['image']['count']; $i++) 
  {
    $form['image'][$i] = array (
      '#markup' =&gt; "&lt;p&gt;$i&lt;/p&gt;",
    );
  }
  // And our button
  $form['image']['more'] = array (
    '#type' =&gt; 'button',
    '#value' =&gt; t('More'),
    '#ajax' =&gt; array (
      'callback' =&gt; 'product_more_images',
      'wrapper' =&gt; 'product_images',
      'method' =&gt; 'replace',
      'effect' =&gt; 'fade',
      'prevent' =&gt; 'submit',
    ),
    '#machine_name' =&gt; 'more_images_button',
  );
}

// Now callback function is trivial
function product_more_images($form, $form_state) {
  return $form['image'];
}


Of course it's only a sketch, with all off topic parts removed.