5

./bin/importmap pin jquery

pinned jquery using this command

In application.js file

import jquery from "jquery"
window.jQuery = jquery;
window.$ = jquery;

added these lines

but in my view file I am getting $ undefined

<script>  
  $(document).ready(function() {
    $("#user_primary_email").focusout(function(){
      $("#user_email").val($(this).val());
    });
  });
</script>

2 Answers 2

4

In my script tag I added type="module"

<script type="module">  
  $(document).ready(function() {
    $("#user_primary_email").focusout(function(){
      $("#user_email").val($(this).val());
    });
  });
</script>

And now it is working, I don't know why?

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

Comments

2

For future visitors...

Here is how you solve this:

  1. Pin jquery
    bin/importmap pin jquery

  2. Use jsdelivr.net or local file in importmap.rb
    jspm won't work for some unknown reason

    a) pin "jquery", to: "https://cdn.jsdelivr.net/npm/jquery/dist/jquery.js"

    b) pin "jquery", to: "jquery.js"
    if you use a local file, you need to download jquery.js to app/javascript/jquery.js

    You can also pin to a specific version if you want that
    c) pin "jquery", to: "https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.js"

  3. In application.js file you only need to add this
    import "jquery"

  4. When you want to use jquery in a view, you need use type="module" on the script tag

<script type="module">

 $(document).ready(function(){
   console.log($)
 })
</script>

2 Comments

Why is type="module" required?
The script type="module" attribute is required for using jQuery with importmaps because importmaps are a way to load and manage JavaScript modules.

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.