0

I would like to disable the form submit button until all inputs have a value in them. My view has these inputs:

  <%= form_for @item, html: { enctype: "multipart/form-data", id: "upload-data" } do |f| %>
   <%= f.text_field :name %>
  <% end %>

I then run this validate() function with every keyup event:

$(document).ready(function() {
  validate();
  $('input').on('keyup', validate);
});

function validate() {
  var input = $('input');
  var isValid = false;
  $.each(input, function(k, v) {
    if (v.type != "submit") {
      isValid = (k == 0) ?
        v.value ? true : false : isValid && v.value ? true : false;
    }
    if (isValid) {
      $("input[type=submit]").prop("disabled", false);
    } else {
      $("input[type=submit]").prop("disabled", true);
    }
  });
}

Though the same code works here it does not work in my Rails view. It stays disabled. What am I overlooking?

4
  • 1
    maybe because of turbolinks in rails you just can't just copy paste the javascript you need to adapt it into turbolinks script and syntax try this $(document).on('ready turbolinks:load', function() {}); instead $(document).ready(function() {}); Commented Sep 11, 2021 at 11:33
  • 1
    could u add more detail like where did you put the javascript, and the html page source? Commented Sep 12, 2021 at 5:01
  • the javascript is in the old app/assets/javascript directory for Rails 5.2.4, and the page source is in app/views/items/new Commented Sep 13, 2021 at 4:12
  • Why not just use HTML5 validations? developer.mozilla.org/en-US/docs/Learn/Forms/Form_validation Commented Sep 14, 2021 at 18:09

1 Answer 1

1

maybe because turbolinks, in rails you can't just copy paste the javascript you need to adapt it into turbolinks script and syntax

you could try to change your script from

$(document).ready(function() {

});

into

$(document).on('ready turbolinks:load', function() {

})
Sign up to request clarification or add additional context in comments.

3 Comments

still no go. any idea how i could troubleshoot this?
did the script loaded? you can try it by putting console.log("loaded") inside the bracket
the script is definitely loading, the problem is that it fires once when the page loads, and then never fires again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.