user3673744 user3673744 - 5 months ago 32
Javascript Question

How to get ids of checked checkboxes that are generated dynamically in jquery

My problem is that when i click on the button after checking some checkboxes, the result shows that, there is a loop problem. the id of the last checked box have been push into the array instead.

My html looks like this:

<h1>Batch Testing</h1>

<div id="batch_schedule_wraper"></div>
<input type="button" id="getCheckedBoxtBtn" value="Get Checked Ids" />


Here is my javascript:

$(document).ready(function() {


$('#getCheckedBoxtBtn').on('click', function() {

var selected = [];

$("div#batch_schedule_wraper input[type=checkbox]").each(function() {
if ($(this).is(":checked")) {
selected.push($(this).attr('id'));
}
});

alert(selected);
});

var sortedIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (var i = 0; i < sortedIds.length; i++) {

$("#batch_schedule_wraper").append("<div class='checkbox'>" +
"<label class='block'>" +
"<input name='form-field-checkbox' type='checkbox' class='ace input-lg remove_widget' id=''/>" +
"<span class='lbl bigger-120'>Batch</span>" +
" </label>" +
"</div>"

+
"</div>");
$("[name='form-field-checkbox']").attr("id", sortedIds[i]);

}
});

Answer Source

What you are doing here is: You are appending a check box element into your div, and then setting id for all the check boxes that has name as "form-field-checkbox" inside your div. So it sets the same id for all the check boxes inside the div.

So at the end of your loop, all your check boxes will have the same id: "10".

You can solve it by setting id just for the current element and append it in your div.

for (var i = 0; i < sortedIds.length; i++) {

    $("#batch_schedule_wraper").append("<div class='checkbox'>" +
      "<label class='block'>" +
      "<input name='form-field-checkbox' type='checkbox' class='ace input-lg remove_widget' id='" + sortedIds[i] + "'/>" +
      "<span class='lbl bigger-120'>Batch</span>" +
      " </label>" +
      "</div>" +
      "</div>");
  }

To bind event on individual check box, do this

    for (var i = 0; i < sortedIds.length; i++) {

  var $checkDiv = $("<div class='checkbox'>" +
      "<label class='block'>" +
      "<input name='form-field-checkbox' type='checkbox' class='ace input-lg remove_widget' id='" + sortedIds[i] + "'/>" +
      "<span class='lbl bigger-120'>Batch</span>" +
      " </label>" +
      "</div>" +
      "</div>");

      $checkDiv.find("input").on("change", function(evt) {
            //do whatever you want
            //alert($(this).attr("id"));
      });

    $("#batch_schedule_wraper").append($checkDiv);
  }