0

I'm creating a web project in Ruby on Rails. I have a main.js file stored inside /app/assets/javascripts/, in which I've developed a little script to reset the forms.

The script works perfectly just while I don't surf around the web. If I change the current page, the script doesn't work anymore. To get it work again, I have to reload the page through the browser (using Cmd+R or F5).

The main.js script is supposed to be compiled and it should be available in all the pages in the project, isn't it?

What's wrong?

The code in main.js:

// Get rid of data in forms
jQuery.fn.reset = function () {
$(this).find("input, textarea, select").each (function() {
    if ($(this).is(':checkbox')) {
        $(this).prop('checked', false);
    }
    else {
        if (!$(this).is(':hidden') && !$(this).is(':submit')) $(this).val('');
    }
});
}

$(document).ready(function() {

    // Cancel button in forms
    $(".cancel").click(function() {
        $(document).reset();
    })
});

Application.js:

//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require turbolinks
//= require_directory .
mu is too short
  • 396,305
  • 64
  • 779
  • 743
Rubén Jiménez
  • 1,765
  • 5
  • 17
  • 27

1 Answers1

1

Turbolinks is the "problem". $(document.ready is only triggered on full page reloads. You need to also listen for $(document).on('page:load', ...)

See comment #3 on OP (above).

Meltemi
  • 36,348
  • 48
  • 182
  • 274
  • Aaah. Apparently if your "answer" has a link back to SO it'll become a comment and not an answer. So my answer is actually comment #3 on OP. – Meltemi Sep 13 '13 at 01:17