0

I'm trying to get an AJAX-enabled form working. Users should be able to tab between fields using the keyboard, and when a user tabs to the next element, I want the name span after the previous-focused element to update via AJAX.

function my_form() {

    ...

    $form['entry_fieldset']['entry_ids'][] = array(
      '#type' => 'textfield',
      '#field_suffix' => "<span class='entry_name'>John Doe</span>",
      '#ajax' => array(
        'callback' => '_update_name_callback',
       ),
    );

    ...

    return $form;
}

Above, you can see that the span is after the textfield and contains a name. The AJAX will be called when focus is lost. Since I only want the span to update, I'm trying to use AJAX commands in the callback:

function _update_name_callback($form, &$form_state) {
  $id = $form_state['triggering_element']['#id'];
  $entry = $form_state['triggering_element']['#value'];

  // update name based on value.
  $name = 'New Name';

  // Set the innerText of the span element.
  // Calls jQuery: $.('selector').text('New Name');
  $commands[] = ajax_command_invoke("#{$id} + span.entry_name", 'text', [[$name]]);

  return array('#type' => 'ajax', '#commands' => $commands);
}

But for some reason, the updates don't show until the form is rebuilt. I'm pretty new to this, and I don't know what I'm doing wrong. I've spent days on this.

I've also tried this using 'wrapper' => 'entry-container', 'method' => 'replace' where the container is on the item, but it has the same issue, and I'm not sure it'd work anyway because I'm changing something that is a field_suffix, not the actual textfield.

What do I need to change so that the single piece is updated at this time, rather than waiting for a submit button to be clicked? What am I doing wrong?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.