-1

I have a drop-down (<select id="typeselect">) with an inline onchange event handler to alert the selected option. Why do I get the error: undefined is not a function?

Demonstration below:

(function($) {

  function test() {
    var selected_option = $('#typeselect option:selected');
    alert(selected_option);
  }

})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="typeselect" onchange="test()">
  <option>(Select)</option>
  <option value="oi">Outgoing invoice</option>
  <option value="ii">Incoming invoice</option>
  <option value="oc">Outgoing Credit Nota</option>
  <option value="ic">Incoming Credit Nota</option>
</select>
showdev
  • 28,454
  • 37
  • 55
  • 73
user3788334
  • 31
  • 2
  • 8
  • 5
    Maybe `test` is not defined in global scope or you didn't load jQuery. However, the error seems to indicate that it originates somewhere else, not in what you posted. Maybe reading the jQuery tutorial will help: http://learn.jquery.com – Felix Kling Apr 13 '15 at 19:10
  • 3
    You should learn how to use your browser's developer tools, and use the Javascript console to help your troubleshooting. You will get a better error message and if your still stumped, add that to your question. – Dan Apr 13 '15 at 19:13
  • ^ https://developer.chrome.com/devtools/docs/javascript-debugging – Felix Kling Apr 13 '15 at 19:18
  • Updated the post! Hope it helps. I'm using the console from chrome to troobleshoot my error. – user3788334 Apr 13 '15 at 19:20
  • Question has been reworded to fit the rules – user3788334 Apr 13 '15 at 19:30
  • As Felix King mentioned, `test()` is not in the global scope ([see this post](http://stackoverflow.com/questions/2464635/what-does-function-jquery-do-mean)) yet you are calling it from the global scope ([see this post](http://stackoverflow.com/questions/1315924/jquery-calling-a-function-inline) or [this post](http://stackoverflow.com/questions/3371632/why-cant-i-use-onclick-to-execute-a-function-inside-a-jquery-document-ready)). I suggest adding a "change" event handler at the same scope as your function, something like: `$('#typeselect').on('change',test});` – showdev Apr 13 '15 at 23:55
  • I removed some of your original code for the sake of brevity/clarity but, if you are interested, these posts may also be informative: [jQuery document.ready vs self calling anonymous function](http://stackoverflow.com/questions/3259496/jquery-document-ready-vs-self-calling-anonymous-function) and [function inside $(document).ready function](http://stackoverflow.com/questions/6780890/jquery-function-inside-document-ready-function) – showdev Apr 14 '15 at 00:17

1 Answers1

2

Thank you showdev for the answer! And thank you everyone else for the help you provided!

    $('#typeselect').on('change',test});

worked perfectly! :D

user3788334
  • 31
  • 2
  • 8