2

I'm developing a Rails application and put some js to enable the submit button only if the user types in something in the inputs. Then, I used $(document).ready to call the function. It works fine when I first load up the application. But as soon as I go to a new link, it stops working. I've been looking around a lot and none of the suggested answer seems to help. Any help on this would be much appreciated!

application.js

//= require jquery
//= require popper
//= require bootstrap-sprockets
//= require rails-ujs
//= require turbolinks
//= require_tree .
//= require_self

// Global application events
var applicationHandler = (function() {
  // Per Design specs, a submit button on a form should be disabled until all form fields are filled out
  var verifyFormInputsBeforeSubmit = function() {
    $('form input').on('keyup', function() {
      var inputLengths = 0;
      var allInputs = $('input:not([type="submit"]');

      allInputs.each(function() {
        if ($(this).val()) {
          inputLengths += 1;
        }
      });

      if (inputLengths == allInputs.length) {
        $("input[type=submit]").removeAttr("disabled");
      } else {
        $("input[type=submit]").attr("disabled", "disabled");
      }
    });
  };

  return {
    verifyFormInputsBeforeSubmit: verifyFormInputsBeforeSubmit
  };
})();

$(document).ready(function() {
  console.log("wee");
  applicationHandler.verifyFormInputsBeforeSubmit();
});

How I'm linking to the new page:

<%= link_to "Forgot password?", new_password_path(resource_name), class: 'small float-right' %>

It should be noted that wee shows up on the console when I load the index page, but nothing shows when I go to the forgot password page. If I refresh the forgot password, I see the wee in the console and the js runs.

Ccyan
  • 897
  • 8
  • 26
  • 2
    It is because of turbolinks gem. Try to replace `$(document).ready(function()` with `$( document ).on('turbolinks:load', function()` – Vasilisa Jul 13 '18 at 15:10
  • Thanks, that worked perfectly. I never knew the turbolinks gem would do this! – Ccyan Jul 13 '18 at 15:12

1 Answers1

4

I believe this is related to turbolinks, the page doesn't actually reload, so you need to run your code through a different event: Rails 5: how to use $(document).ready() with turbo-links

ioev
  • 68
  • 6