开发者

jquery check checkboxes based on php array

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 sor开发者_JAVA技巧ts 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..


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.


<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/


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.'>';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜