roeland
roeland

Reputation: 6336

Autofocus not working after updating form with ajax

In Rails 5.2 I created a form (my first) with the form_with helper. By default this is remote: true.

This form contains one input with autofocus="autofocus".

After a validation error the same form is returned with ajax. I use this to update the form:

document.addEventListener('ajax:success', (event) => {
  const [data, status, xhr] = event.detail;
  const form = document.getElementById('form-signin')
  form.parentNode.innerHTML = xhr.responseText
})

This works, but autofocus doesn't work now. (it does the first time)

Is there a way to get autofocus working automatically or should I do this manually in the js code above?

Everything works with local:true, but since this is no longer the default I would like to try the new way. There isn't much documentation on how to correctly handle a ajax response. (At first I thought turbolinks would do this for me)

Solution: The answer below works, but I found a better solution that makes it a lot easier. It works without writing custom javascript: https://github.com/turbolinks/turbolinks-rails/issues/40 https://github.com/jorgemanrubia/turbolinks_render

Upvotes: 0

Views: 625

Answers (1)

Enrico Deleo
Enrico Deleo

Reputation: 388

Autofocus is triggered when page loads, hence if your page is already loaded you won't get the expected result.

You can manually focus the first autofocus element when the ajax call finishes from within your callback with something like:

const autofocusedElements = document.querySelectorAll('input[autofocus]');
if (autofocusedElements.length) {
  autofocusedElements[0].focus();
}

Upvotes: 2

Related Questions