I cannot seem to get this to work. I am using jquery to create an html select, and I want some code to execute when its value changes.
code follows:
<script type ="text/javascript">
var firstweddingturn = '400';
$('#weddingturn').change(function() {
alert ("Wedding select change triggered!");
//var wedturn = $('#weddingturnselectid').val();
//$('#div3').append('<br>Wedding turn selected, ' + wedturn + '</br>')
});
$(document).ready(function() {
var html = [];
html[html.length] = '<select name="weddingturn" id="weddingturn">';
var a = firstweddingturn;
var b = Number(firstweddingturn) + 16;
while (a < b) {
// do some code
html[html.length] = '<option name="asdf" value = "1">' + a + '</option>';
a++;
} // end while
html[html.length] = '</select>';
$('#div1').append(html.join(''));
});
</script>
What am I doing wrong?
You need to use
.delegate()(or.live()) since you are adding the select dynamically. When you attach an onChange handler with.change()it is only attached to existing matching elements, not elements which are added later on. To attach an event to all matching elements including those added to the page later, you use the.delegate()function, like this:However, as some people point out, you can merely attach the event handler immediately after adding the
<select>to the DOM. That way, you can still use.change()and your code should run faster.