No return on$('input:checkbox').change(fun

2019-09-06 11:51发布

This question already has an answer here:

I am testing a second solution that has been provided to me here, for checking and recording each check box that has been checked. First solution works like a charm but the second more efficient solution does not even run.

for (x in aL.results) {
  aLIds.push(aL.results[x].listing_id);
  aLTitles.push(aL.results[x].title);
  aLQuantities.push(aL.results[x].quantity);
  aLDescs.push(aL.results[x].description);
  aLTaxPaths.push(aL.results[x].Tax_path);
  aLTaxIds.push(aL.results[x].Tax_id);
  aLTags.push(aL.results[x].tags);
  aLUrls.push(aL.results[x].url);
  aLPrices.push(aL.results[x].price);
  aLViews.push(aL.results[x].views);
  aLHearts.push(aL.results[x].num_favorers);

  $('#tblListings').append(
    '<tr>' + '<td><input type="checkbox" name="updateListings[]" value=' + x + ' ></td>' + '<td>' + aLQuantities[x] + '</td>' + '<td>' + aLTitles[x] + '</td>' + '<td>' + aLPrices[x] + '</td>' + '<td>' + aLViews[x] + '</td>' + '<td>' + aLHearts[x] + '</td>' + '</tr>'
  );
}

$('input:checkbox').change(function() {
    alert('ah');
    var uLIndex = $('input:checkbox:checked').map(function() {
        return this.value;
    }).get();
    console.log(uLIndex);
});

1条回答
Deceive 欺骗
2楼-- · 2019-09-06 12:35

For dynamically create element we can not bind event directly do something like this or live function and this function is removed in 1.9 version so make sure what version of jquery you are using or many ways you can find out on jquery official site

$('body').on("change","input:checkbox",function() {
    alert('ah');
  var uLIndex = $('input:checkbox:checked').map(function() {
    return this.value;
  }).get();
  console.log(uLIndex);
});

Updated

Add a class to checkbox check

$('#tblListings').append(
    '<tr>' + '<td><input class="check" type="checkbox" name="updateListings[]" value=' + x + ' ></td>' + '<td>' + aLQuantities[x] + '</td>' + '<td>' + aLTitles[x] + '</td>' + '<td>' + aLPrices[x] + '</td>' + '<td>' + aLViews[x] + '</td>' + '<td>' + aLHearts[x] + '</td>' + '</tr>'
  );

And than bind event on all checkbox with class name check as below.

$('body').on("change",".check",function() {
    alert('ah');
  var uLIndex = $('input:checkbox:checked').map(function() {
    return this.value;
  }).get();
  console.log(uLIndex);
});
查看更多
登录 后发表回答