rod james
rod james

Reputation: 449

ReferenceError on a Function

I just want a quick question regarding javascript. I saw on w3schools the onchange on select to run a function. I am still learning Javascript and jQuery so if I miss something, please tell me.

<select id="mySelect" onchange="myFunction()">
.....
</select>

Then on my external JS File:

$(document).ready(function () {
.....
  console.log("TEST01");
  function myFunction() {
    console.log("TEST02");
  }
.....
});

When I load my page, on console, I can see TEST01 printing but when I made some changes in select, it gives me ReferenceError myFunction is not defined

Upvotes: 1

Views: 44

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

Instead of inline callback, do it in jQuery way listening on the onChange callback with $('#mySelect').on('change', myFunction)

$(document).ready(function () {
  console.log("TEST01");
  
  function myFunction() {
    console.log("TEST02");
  }
  
  $('#mySelect').on('change', myFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="mySelect">
 <option>1</option>
 <option>2</option>
</select>

Upvotes: 1

Related Questions