theCamburglar
theCamburglar

Reputation: 343

HTML <select> JQuery .change not working

Alright I don't see why this isnt working. It seems pretty simple.

Here is my drop-down menu:

<div>
    <form>
        <select id='yearDropdown'>
            <c:forEach var="years" items="${parkYears}">
                <option value=/events.html?display_year=${years}<c:if test="${currentYear == years}">selected="selected"</c:if>>${years}</option>
            </c:forEach>
        </select>
    </form>
</div>

and here is the JavaScript

$("#yearDropdown").change(function () {
    alert('The option with value ' + $(this).val());
});

Right now I just want to get it working so I can add functionality. Thanks!

Upvotes: 16

Views: 60812

Answers (4)

Alex
Alex

Reputation: 35407

That code is syntactically correct. Most likely running it at the wrong time.

You'll want to bind the event when the DOM is ready:


Native JS/DOM

window.addEventListener('DOMContentLoaded', () => {
    const yearDropDown = document.getElementById('yearDropdown');
    yearDropDown.addEventListener('change', () => { 
        alert(yearDropDown.value)
    });
});

jQuery

$(function(){ /* DOM ready */
    $("#yearDropdown").change(function() {
        alert('The option with value ' + $(this).val());
    });
});

Or, use live:

$("#yearDropdown").live('change', function() {
    alert('The option with value ' + $(this).val());
});

Or, use delegate:

$(document.body).delegate('#yearDropdown', 'change', function() {
    alert('The option with value ' + $(this).val());
});

Or, if you're using jQuery 1.7+:

$("#yearDropdown").on('change', function() {
    alert('The option with value ' + $(this).val());
});

Nonetheless, it is usually best to execute script once the browser has finished rendering Markup.

Upvotes: 43

Alberto De Caro
Alberto De Caro

Reputation: 5213

I have tried your code in jsFiffle. I manually added some years as options. It works right.

Just bind the .change event in the $(document).ready:

$(document).ready(function(){
  $("#yearDropdown").change(function () {
      alert('The option with value ' + $(this).val());
  });​
});

Upvotes: 3

Logard
Logard

Reputation: 1513

Not sure if this will help, but you could try this:

    $("#yearDropdown").live("change", function () {
    alert('The option with value ' + $(this).val());
});

Upvotes: 0

Louis B.
Louis B.

Reputation: 2368

Your code is correct and is working for me, see here: http://jsfiddle.net/mobweb/2Skp9/

Are you sure jQuery has been loaded properly?

Upvotes: 0

Related Questions