Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 7 jquery: Uncaught ReferenceError: $ is not defined

I added jQuery to my Rails 7.0.2.4 project by the following:

First run command ./bin/importmap pin jquery, to add the following line in config/importmap.rb:

pin "jquery", to: "https://ga.jspm.io/npm:[email protected]/dist/jquery.js"

Then add lines to import jQuery in app/javascript/application.js:

import '@hotwired/turbo-rails'
import 'controllers'
import 'bootstrap'

import jquery from 'jquery'
window.jQuery = jquery
window.$ = jquery

My view with javascript:

<%= form_with(model: @micropost) do |f| %>
  <%= render 'shared/error_messages', object: f.object %>
  <div class='field'>
    <%= f.text_area :content, placeholder: 'Compose new micropost...' %>
  </div>
  <%= f.submit 'Post', class: 'btn btn-primary' %>
  <span class='image'>
    <%= f.file_field :image %>
  </span>
<% end %>

<script type='text/javascript'>
  $('#micropost_image').bind('change', function() {
    if (this.files[0].size/1024/1024 > 5) {
      alert('Maximum file size is 5MB.  Please choose a smaller file.')
      $('#micropost_image').val('')
    }
  })
</script>

When the view is loaded, Chrome console shows:

Uncaught ReferenceError: $ is not defined at (index):103:3

And when I select a file bigger than 5MB, no error message is popped up, so I think the script isn't run.

How to fix it?

like image 424
user21916 Avatar asked Aug 07 '26 13:08

user21916


1 Answers

try this:

window.onload = function() {
  $("#micropost_image").bind("change", function() {
    const size_in_megabytes = this.files[0].size/1024/1024;
    if (size_in_megabytes > 5) {
      alert("Maximum file size is 5MB. Please choose a smaller file.")
      $("#micropost_image").val("");
    }
  });
}
like image 200
LAN Avatar answered Aug 09 '26 03:08

LAN