1

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

rod james
  • 369
  • 3
  • 13
  • 4
    The functions called in inline listeners must be global. `myFunction` inside `$(document).ready(...)` is not global, see https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Teemu Feb 10 '21 at 07:07
  • Oh . That worked. Did not know that. Thank you. I am still learning both. Thanks for the quick response. – rod james Feb 10 '21 at 07:08
  • `myFunction()` is declared inside another function (the `$(document).ready` handler), so it will only be available from within that function. From your HTML `onchange`, which executes in the global scope, it's invisible. You should use `$("#mySelect").change(myFunction)`. – Jeremy Thille Feb 10 '21 at 07:09
  • Instead of inline listeners, you should attach the events with [jQuery](https://api.jquery.com/on/#on-events-selector-data-handler) (as you seem to use it). – Teemu Feb 10 '21 at 07:10

1 Answers1

1

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>
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Siva K V
  • 10,561
  • 2
  • 16
  • 29