I wrote some jQuery code in an external file, with the goal to match each <select> tag in the page where the script is included.
My goal would be to include the script reference in the <head> tag of the target pages and “run” the jQuery code without having to call any function.
I have seen several examples with external jQuery code, but all call a function to execute the (external) code.
If I use “plain” javascript, like simple alerts, they are executed without problem. When I try with my jQuery code, nothing happens.
Here is my external jQuery file:
$(function() {
$("select").focus(function() {
alert('selected...');
}).change(function() {
alert('changed...');
})
});
Even if I do not use $(function() at the beginning I always get the exception “Object Expected” at the first occurrence of $, while even leaving $(function() and inside the brackets a simple alert it works.
How the external file should be developed?
I tested the external script inline in a test page and it works fine.
It makes no difference where your code is written, either inline in your HTML page, or included via
<script src='...'>.The issue then would be that jQuery has not yet been included by the time your code is being executed. Take a look at the order which you’re including your files, and ensure that jQuery comes before this code which relies upon it.