Pregunta

I am using nested_forms with Rails 4 along with turbo-links + jQuery plugin to make it restart on page loads. Once I add a nested field with markup that should triggers events, it fails to do some, seeming like only content on initial page load can trigger the js events.

Example:

$(document).ready(function(){
  $('.address_input_type').on('change', function(){
    showAppropriateAddressFields(this);
  })
});

So function showAppropriateAddressFields will fire if the '.address_input_type' is on the page initially but if added in afterwards it fails. Any ideas?

¿Fue útil?

Solución

As the elements are newly inserted, you'll need to use event delegation:

$(document).ready(function(){
  $(document).on('change', '.address_input_type', function(){
    showAppropriateAddressFields(this);
  })
});

Try to find a closer parent element than document (such as a container div) to use as the selector, as using document isn't very efficient.

Otros consejos

If you query the DOM at the time of page load for a class, you will return an array-like-object of nodes that will not update itself when other nodes with that class are later added. Append it to the page from the beginning and set it's style "display: none".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top