Ben Ben -4 years ago 61
HTML Question

Basic Javascript / jQuery Works jFiddle, but Not my Browser

I am not new to programming but I am new to Javascript and jQuery.

In my attempts to write the most basic thing, I wrote the below.

If I copy the jQuery include + my javascript and the HTML to jsFiddle, it works. When you select something on the dropdown you get the alert box.

But opening the .html file in my browser, it does not work. You can change the selection all day long and nothing happens.

I feel like this is the most basic thing but I haven't been able to figure it out. What dumb beginner mistake am I making? Javascript is client-side, so it should work I would think. I am using Chrome if it matters but same result in IE. Javascript is enabled in both.

<html>

<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#selections').change(function() {
alert('Test');
});
</script>
</head>

<body>

<select id="selections">
<option>Options...</option>
<option value="zero">zero</option>
<option value="one">one</option>
</select>

</body>

</html>

Answer Source

You have to put your script inside a $(document).ready() function. In JQuery, this ensures that all the events are being attached after the elements of the page has been loaded. Please see revised code below:

$(document).ready(function() {
    $('#selections').change(function() {
        alert('Test');
    });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download