Drupal 9 - Uncaught ReferenceError: jQuery is not defined

3.9k views Asked by At

I am trying to use an external Javascript library areYouSure in Drupal 9. I am getting the error "Uncaught ReferenceError: jQuery is not defined".

My php code for form looks as below.

<?php

function raco_inventory_purchase_form($eid)
{
    $out = 
    '
    <script src="/core/assets/vendor/jquery/jquery.min.js"></script>
    <script src="/libraries/areyousure/jquery.are-you-sure.js"></script>
    <script src="/modules/custom/racoinventory/js/racoinventory.js"></script>
    
    <body>
        <form id="myform" autocomplete="off" action="/racoinventory/purchase/entries/' . $eid . '" method="post">
            <input type="text" id="yourname" name="yourname" value="' . '" placeholder="Enter your name">
            <br><br>
            <input type="button" value="Save" onclick="racoinventory_save_data(this);" />
        </form>

        <script>
          jQuery(function() 
          {
            jQuery("#myform").areYouSure(
              {
                message: "It looks like you have been editing something. "
                       + "If you leave before saving, your changes will be lost."
              }
            );
          });
       </script>
     </body>
    ';
    
    return $out;
}
?>

My library file looks as below

# Custom module library for general purposes.
racoinventory:
  css:
    component:
      css/racoinventory.css: {}
  
  js:
    /libraries/raco/racocommon.js: {}
    js/racoinventory.js: {}
    /libraries/areyousure/jquery.are-you-sure.js
    
  dependencies:
    - core/jquery
    - core/jquery.once

And the javascript code looks as below

function racoinventory_save_data()
{
    alert("You hit Save button");
    jQuery('#myform').trigger('rescan.areYouSure');
    return true;
}

With this code in place, When I load the page , I get below error.

Uncaught TypeError: jQuery(...).areYouSure is not a function

I am not sure what is going wrong here. Can somebody please help me to figure out the issue.

1

There are 1 answers

0
Sumit Kumar On

IMO you can try to wrap your code in

(function ($,jQuery) {
  $(document).ready(function(){
   Code here

  });
})(jQuery);

However, you can check jQuery library version and can load jQuery at bottom.