Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
91
rated 0 times [  97] [ 6]  / answers: 1 / hits: 58465  / 12 Years ago, tue, june 26, 2012, 12:00:00

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!


More From » jquery

 Answers
139

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.


[#84643] Monday, June 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jeanettee

Total Points: 209
Total Questions: 97
Total Answers: 98

Location: Papua New Guinea
Member since Thu, Jul 9, 2020
4 Years ago
;