Reputation: 4434
I am using JavaScript to generate some HTML tables on the fly. After filling out this dynamic table, I employ jQuery to 'grab' some of the inputs and do some small calculations for form validation. However, my jQuery selector does not work with the dynamic HTML form. Can anyone give me some suggestions? Thanks!
Here is the code:
<script>
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');
// jQuery selector, which does not work dynamically
$('select[name=CAM_1_'+i+']').change(function() {
var ss1=$(this).val()
alert(ss1)})
</script>
Upvotes: 0
Views: 563
Reputation: 5793
<script>
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');
// jQuery selector, which does not work dynamically
$('select[name=CAM_1_'+i+']').live("change",function() {
var ss1=$(this).val()
alert(ss1)})
</script>
so basically you need to use live method of jquery for dynamically generated html.
Upvotes: 0
Reputation: 318182
<script type="text/javascript">
$(function() {
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>')
.appendTo('.table')
.on('change', function() {
alert(this.value);
});
});
</script>
Upvotes: 1
Reputation: 10702
I wanted to replicate your problem, but for me it works completely fine. I did have to add the closing brackets (})
) as these seemed to be missing from what you posted. Do you get any errors in the console. Check to see if you get any errors in the JavaScript console and whether you're using the latest version of jQuery.
<table class="table"></table>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script>
i = 0;
//generate HTML table
$('<tr><th><label for="id_CAM_1">Input:</label></th><td><select name="CAM_1_'+i+'" id="id_1_'+i+'"><option value="1">Option 1</option><option value="2">Option 2</option></select></td></tr>').appendTo('.table');
// jQuery selector, which does not work dynamically
$('select[name=CAM_1_'+i+']').change(function() {
var ss1=$(this).val()
alert(ss1)
});
</script>
Upvotes: 1
Reputation: 146302
The following will detect all changes of all select
elements that have a name that starts with CAM_1_
in your tableSelector
$('tableSelector').on('change', 'select[name^="CAM_1_"]', function() {
alert(this.value);
});
Upvotes: 1