0

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.

4
  • how does your $checkboxarray look like? Commented Oct 4, 2012 at 7:24
  • 1
    $('input[name ="selections[]"]') selects all the checkboxes, not some particular one. Try simply $('#' + elem.name).attr('checked', 'checked') instead. Commented Oct 4, 2012 at 7:25
  • Thank you $('#' + elem.name).attr('checked', 'checked') is more specific and it works better. Commented Oct 16, 2012 at 10:34
  • @MihaiIorga vardump($checkboxarray) returns something like: array(4) { [0]=> array(2) { ["id"]=> string(1) "1" .... Commented Oct 16, 2012 at 10:40

3 Answers 3

1

You can do this:

$.each(checkboxarray, function (i, elem){
    if($('#'+elem.name) != 'undefined'){
        $('#'+elem.name).attr('checked', true);
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can look for the id attribute directly in your selector:

$.each(checkboxarray, function (){
        if($('#' + this.name).length){
            $('#' + this.name).attr('checked','checked');
        }
    });
});

Comments

1

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

1 Comment

true no need for jQuery . I found it easier however to use it, as array seemed somewhat multidimensional such that I would have required nested for loop s for in_array to work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.