JavaScript Working Only After Page Reload when Trying to Add Table Rows via link_to_add_fields method

What is the problem? My JavaScript doesn’t work. Turbolinks is good, but it can be a wee bit annoying at times – well it’s annoying because things don’t work straight off the bat – the magic doesn’t work so good anymore, and us developers have to roll up our sleeves and take a look under the car to find out what is going wrong and how we can fix it.

This is one such occasion: when the user clicks a link, I want a new form to pop up. How do I do this? Easy, just add some javascript (via Jquery) but then I find that it doesn’t work – and it only works after the page reloads. Now that’s a bit of a pain. I don’t want users to hit refresh just so they can add a record. It’s annoying, and more than that, they start complaining as all users are wont to do.

Why is this happening?

This problem occurs because the click handler on a particular item attaches only after that item is drawn and exists. If you try to attach the handler before the item actually exists then you won’t have attached anything. So therefore you can only attach it after the page loads.

So for Rails 5, I did this which solved my problem immediately:


$(document).on('turbolinks:load', function(event)
    {
        $('form').on( 'click', '.remove_fields', function(event){
        $(this).prev('input[type=hidden]').val('1');
        $(this).closest('tr').hide();
        event.preventDefault();
        }); // end call back function

  $('form').on('click', '.add_fields', function(event){
    time = new Date().getTime();
    regexp = new RegExp($(this).data('id'), 'g');
    $(this).before($(this).data('fields').replace(regexp, time));
    event.preventDefault();
    })
    });

// Useful reference: https://stackoverflow.com/questions/17600093/rails-javascript-not-loading-after-clicking-through-link-to-helper

Written on March 31, 2018