0
votes

I'm testing Bootstrap Modal example "live demo" and I've included bootstrap jquery and js in bootstrap starter template, and also the custom javascript:

$('#myModal').on('shown.bs.modal', function () {
  $('#myInput').focus()
})

but the modal run from my text editor doesn't show like the one on their website does. I click the button and nothing happens. I've tried using Google Chrome Inspector/console and it shows:

Uncaught ReferenceError: $ is not defined

at the line where the function starts. When I remove the custom js, it doesn't show error but still the modal doesn't show on Chrome, Edge or Firefox.

My code is just the combination of Bootstrap starter template and its modal live demo code in the body so there's no need to post the code here.

Also, please note that I could make the code work (the button works like the example shown on boostrap website) by assigning an id to the button:

 <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal" id="button">

then add a custom function later:

<script type="text/javascript">
  $("#button").click(function() {
      $('.modal').modal('show');
  });
</script> 

However, that's not the same as the sample code provided by Bootstrap.

3
you forgot to load jquery.min.js - RAUSHAN KUMAR
you may please mention your html code also - Chirag Suthar
You must use Jquery before bootstrap.js - Morteza
Thank you guys. Yes, the error was because the custom js was put before the jquery was loaded. If I put it below the links to jquery by bootstrap, the error doesn't show. However, the button still doesn't do anything. - Viet

3 Answers

0
votes

Generally, this error occurs because you're trying to use JQuery without having referenced it in your project first.

Try adding the following to the top your page:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
0
votes

Thank you all for your suggestions. I've found out the answer: The sample code by bootstrap has an error:

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>

the data-target="" should contain the id of the modal, which, in this case is #myModal not #exampleModal.

-1
votes

it means you are running your script before document is ready. Try this

$(function(){
   $('#myModal').on('shown.bs.modal', function () {
     $('#myInput').focus()
   })
});