i generate one dropdown box through button click event. In this dropdown onchange event does not fire. Can anyone help me why this is heapped? code is below
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#pin').click(function() {
var content='<select class="pincode"><option value="1">1</option><option value="2">2</option></select>';
$("#test").append(content);
});
$(".pincode").change(function(){
alert($(this).val());
});
});
</script>
<style type="text/css">
div {
padding: 35px;
float: left;
}
}
</style>
<title>New Web Project</title>
</head>
<body>
<h1>Dynamic Drop Down using jQuery</h1>
<div>
<select class="pincode">
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div id="test"></div>
<input type="button" id="pin" value="pin" />
You need to use delegation because the element is loaded dynamically and was not there when the event listener was created.
$(document).on('change',".pincode", function(){
alert(this.value);
});
Please notice you have one extra } inside your style tags. Would be better to have this in the CSS file.
Check this link about .on(). In the delegated events part one can read:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to 'the event handler'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With