简体   繁体   中英

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

<input type="checkbox" name="company[]" id="company[]" value="1" checked>

如果您特别希望jQuery做到这一点: 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.'>';
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM