I am doing an edit functionality for a form that contains checkboxes
. i.e I submit data from this form then upon submit there's a provision to edit the previously submitted data.
I have an array containing the submitted checkbox values. So I want for each of the checkboxes whose values are contained in the php array
, I want to have them checked using jQuery
.
I have tried below:
HTML:
<?php
foreach ($selections as $selection) {
echo "<tr><td>" . $selection -> Name . "</td><td><input type=checkbox id=" . $selection -> Name . " name=selections[] value=" . $selection -> id . " /></td></tr>";
}?>
SCRIPT:
var checkboxarray = <?php echo json_encode($checkboxarray) ?>;
$.each(checkboxarray, function (i, elem){
if(elem.name == $('input[name ="selections[]"]').attr('id')){
$('input[name ="selections[]"]').attr('checked','checked');
}
})
However , it does not seem to function correctly.
Help appreciated, Thanks.
$checkboxarray
look like? – Mihai Iorga Oct 4 '12 at 7:24$('input[name ="selections[]"]')
selects all the checkboxes, not some particular one. Try simply$('#' + elem.name).attr('checked', 'checked')
instead. – DCoder Oct 4 '12 at 7:25$('#' + elem.name).attr('checked', 'checked')
is more specific and it works better. – watkib Oct 16 '12 at 10:34vardump($checkboxarray)
returns something like:array(4) { [0]=> array(2) { ["id"]=> string(1) "1" ....
– watkib Oct 16 '12 at 10:40