Hi All

I have a php array containing the mysql values of checkboxes, which has been selected previously. I am trying to do an edit page of sorts which will show the already selected checkboxes, but seem to be having issues with it. I've tried different ways but can't seem to get it working.

Here's my php array of previously selected checkboxes:

Array
(
    [0] => 1
    [1] => 3
)

And here's my checkboxes:

<input type="checkbox" name="company[]" id="company[]" value="1">
<input type="checkbox" name="company[]" id="company[]" value="4">
<input type="checkbox" name="company[]" id="company[]" value="2">
<input type="checkbox" name="company[]" id="company[]" value="3">

I can't seem to work out how to get the checkboxes (from the php array - value 1 and 3) to already be selected..

link|flag

3 Answers

up vote 1 down vote accepted

Here's a server side solution to do it when the page is created.

<?php
function check_checked($index,$check_array){
  if (in_array($index,$check_array)){ echo 'checked="checked"';}
  }
$checked=array(1,3);
?>
<input type="checkbox" name="company[]" id="company[]" value="1" <?php check_checked(1,$checked);?>>
<input type="checkbox" name="company[]" id="company[]" value="4" <?php check_checked(4,$checked);?>>
<input type="checkbox" name="company[]" id="company[]" value="2" <?php check_checked(2,$checked);?>>
<input type="checkbox" name="company[]" id="company[]" value="3" <?php check_checked(3,$checked);?>>

If you were going to do it with JavaScript, I'd suggest printing the array into a JS var with json_encode and going from there. Server side makes more sense, though, since you already have the data to start with.

link|flag
1  
note: add autocomplete="false" if you don't want firefox caching the checked value on page refresh/reload. – Dan Heberden Jun 28 at 0:16
Definitely, that autocomplete attribute is non-standard and won't validate, but FF will really mess with you if you don't include it. @SoulieBaby I wanted to mention this isn't the cleanest or best solution, details-wise, but is suggested as something to build on. It could be refactored in numerous ways. – Alex JL Jun 28 at 20:04

The simpliest way is to do it on the server side:

foreach ($array as $value) {
  $che = $value? "checked":"";
  print '<input type="checkbox" name="company[]" id="company[]" value="1" '.$che.'>';
}
link|flag
<input type="checkbox" name="company[]" id="company[]" value="1" checked>

If you specifically want jQuery to do it: http://www.electrictoolbox.com/check-uncheck-checkbox-jquery/

link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.