Problem
I am creating buttons dynamically in HTML according to database values. I want to bind those buttons to events using dynamically generated jQuery. I have read numerous Q/A's from SO covering dynamic event binding with jQuery but am still failing (eg: Event binding on dynamically created elements?). This makes me wonder if the Flask/jinja-generated HTML is causing an issue?
Template
<div class="buttons">
{% for lvl in lvls %}
<button id="btn_{{ lvl.descriptor }}">{{ lvl.descriptor }}</button>
{% endfor %}
</div>
<script type="text/javascript">
$(document).ready(function() {
# Some code here
});
{% for lvl in lvls %}
$('.buttons').on('click', '#btn_{{ lvl.descriptor }}', function() {
alert("Button clicked!");
});
{% endfor %}
</script>
HTML
<div class="buttons">
<button id="btn_Level 1">Level 1</button>
<button id="btn_Level 2">Level 2</button>
<button id="btn_Level 3">Level 3</button>
</div>
<script type="text/javascript">
$(document).ready(function() {
# Some code here
});
$('.buttons').on('click', '#btn_Level 1', function() {
alert("Button clicked!");
});
$('.buttons').on('click', '#btn_Level 2', function() {
alert("Button clicked!");
});
$('.buttons').on('click', '#btn_Level 3', function() {
alert("Button clicked!");
});
</script>