Drupal 8 Form update text field value with AJAX

The following example will demonstrate how to update text field values with ajax. Use the following in your hook_form_alternate:

Lat-lon

// Create find coordinate button.
$form['field_gc_coordinates']['widget'][0]['subform']['#attributes'] += ['id' => 'lat-long-wrapper'];
$form['field_gc_coordinates']['widget'][0]['subform']['field_city_name']['field_btn_cord'] = [
  '#type' => 'button',
  '#value' => 'Get Coordinates',
  '#ajax' => [
    'callback' => '\Drupal\gc\Controller\AjaxHandlerController::getCoordinates',
    'event' => 'click',
    'wrapper' => 'lat-long-wrapper',
    'progress' => [
    'type' => 'throbber',
    'message' => t('Please wait while fetching coordinates...'),
    ],
  ],
];

Put this code in your AjaxHandlerController.php file.

public function getCoordinates(array &$form, FormStateInterface $form_state) {
  $form['field_gc_coordinates']['widget'][0]['subform']['field_latitude']['widget'][0]['value']['#value'] = latitude_val;
  $form['field_gc_coordinates']['widget'][0]['subform']['field_longitude']['widget'][0]['value']['#value'] = longitude_val;
  return $form['field_gc_coordinates']['widget'][0]['subform'];
}
0/5