HTML <select> JQuery .change not working
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());
});
});
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.