Arif Acar Arif Acar - 24 days ago 8
jQuery Question

How can I check dynamic checkboxes with jquery

I am trying to find the easiest way to check change event checkboxes.

I created checkboxes with php script

PHP:

<div class="form-group">
<div class="col-md-12 servicesCheck" style="margin-top:-10px">
<?php
foreach ($data["languageSchool"]["services"] as $service) {
$required = "";
$checked = "";
if ($service["is_required"] == "1") {
$required = "disabled";
$checked = "checked";
}
echo "<div class='checkbox " . $required . "'>";
echo " <label><input id='services' type='checkbox' " . $checked . " " . $required . " value='" . $service["price"] . "'>" . $service["name"] . "</label>";
echo "</div>";
}
?>
</div>
</div>


JQUERY:

$('#servicesCheck :checkbox').change(function () {
// DO SOMETHING
});


What did I do wrong in my code.

Answer

I think the jQuery selector is wrong. 'servicesCheck' in your HTML is a Class not an Id,

$('.servicesCheck input:checkbox').change(function () {
// DO SOMETHING
});

should work.

Although :checkbox works jQuery documentation says: "it is recommended to precede it with a tag name or some other selector"