I am doing an edit functionality for a form that contains checkboxes
. ie 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.
You can do this:
$.each(checkboxarray, function (i, elem){
if($('#'+elem.name) != 'undefined'){
$('#'+elem.name).attr('checked', true);
}
});
You can look for the id
attribute directly in your selector:
$.each(checkboxarray, function (){
if($('#' + this.name).length){
$('#' + this.name).attr('checked','checked');
}
});
});
You Can also
try
foreach ($selections as $selection) {
$checked = in_array($selection -> Name, $checkboxarray ) ? 'checked="checked"' : '';
echo "<tr><td>" . $selection -> Name . "</td><td><input type=checkbox id=" . $selection -> Name . " name=selections[] value=" . $selection -> id . " ".$checked."/></td></tr>";
}
here $checkboxarray
is your array list of checked
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.