Reputation: 1281
I have dynamically generated checkbox based on JSON data and that is generated by jQuery. I need to dynamically generate checkbox class name. Here is my code that is generated a checkbox
<td>
<label class="switch">
<input
id="chkEnabled"
checked
type="checkbox"
onchange="checkedorUncheked(' + result.data.resultSet[i].id + ',' + count + ')" class="chkEnabled"' + count +' >
<span class="slider round"></span>
</label >
</td>
Here class="chkEnabled"' + count +' I'm incrementing class value but when I call the method checkedorUncheked
I get count value but not getting the class value. Here I console it
` this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).change(function () {
console.log(item2);`
I'm not able to console inside change event because of class name.
Upvotes: 0
Views: 85
Reputation: 458
when HTML elements are dynamically generated, you need to rebind the events of the generated element
Try
this.checkedorUncheked = function (item, item2) {
//console.log('.chkEnabled' + item2);
$('.chkEnabled' + item2).on('change',function () {
console.log(item2);
Use on() method instead of directly using .change(), but in comments as suggested don't generate class, generate Id instead and use the same.
then code becomes
$('#chkEnabled' + item2).on('change',function () {
console.log(item2);
UPDATE
<input
id=' + result.data.resultSet[i].id + '
checked
type="checkbox"
onchange="checkedorUncheked(this);" count=' + count +' >
<span class="slider round"></span>
function checkedorUncheked (e){
var itme1 = $(e).attr('id'); /// for id
var item2 = $(e).attr('count'); // count
if($(e).prop('checked') == true){
//do something
}
else{
/// do another
}
}
Upvotes: 1