I am trying to figure out why the javascript cannot locate the .submit-button from the modal. My javascript is in application.js but I do not understand what I am doing wrong. Am I meant to wrap my JQuery code in something else?
**application.js**// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
import "popper"
import "bootstrap"
$(document).on("click", ".submit-button", function () {
alert("click");
});
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Welcome! Please Log in</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<%= simple_form_for(resource, remote: true, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :email,
required: true,
autofocus: true,
input_html: { autocomplete: "email" }%>
<%= f.input :password,
required: true,
hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length),
input_html: { autocomplete: "new-password" } %>
<%= f.input :password_confirmation,
required: true,
input_html: { autocomplete: "new-password" } %>
</div>
<div class="form-actions">
<%= f.button :submit, "Sign up Now", class: 'btn btn-primary submit-button' %>
</div>
<% end %>
<%= render "devise/shared/links" %>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Log In</button>
<%= button_to(
"Log Out",
destroy_user_session_path,
method: :delete
) %>
</div>
</div>
</div>
</div>
3
Answers
I added
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
between the head tags as I was getting theerror Uncaught ReferenceError: $ is not defined
. I had gem 'jquery-rails' in my gemfile but not sure why rails is doing this, however problem solved.Since you have comment about importmaps in the top of
application.js
, you use this libraryYou can pin jQuery such way (I took URL from your answer, you can use from jsDelivr or other sources)
and import
Do you really need jQuery in 2023?
The browser API’s today are so much better so that it’s just as easy to do without it.
If you’re doing anything more complex you can use Stimulus.