在foreach循环中选中all / uncheck all

时间:2013-05-30 05:19:10

标签: php javascript

请查看此代码。我该如何实现呢?

enter image description here

最近我这样做了 -

<script type="text/javascript">
function CheckPowerAll() {
    if (document.getElementById("PO_ALL").checked == true) {

        document.getElementById("PO_PowerSteering").checked = true;
        document.getElementById("PO_PowerMirrors").checked = true;
    } else {

        document.getElementById("PO_PowerSteering").checked = false;
        document.getElementById("PO_PowerMirrors").checked = false;
    }
}
</script>

<tr>
  <td><input name="PO_ALL" type="checkbox" id="PO_ALL" value="checkbox" onclick="CheckPowerAll()" />
Select all <span class="bold">Power Options</span> </td>
   </tr>
 <tr>
<td><table width="85%" border="0" cellspacing="0" cellpadding="0">
 <tr>
<td class="box2">

   <input name="PO_PowerSteering" type="checkbox" id="PO_PowerSteering" value="Power Steering" />
Power Steering<br />
   <input name="PO_PowerMirrors" type="checkbox" id="PO_PowerMirrors" value="Power Mirrors" />
Power Mirrors <br /></td>
  </tr>
</table></td>
  </tr>
<tr>

但现在我需要填充DB的值。

<input name="PO_ALL" type="checkbox" id="PO_ALL" value="checkbox" onclick="CheckPowerAll()" />
Select all <span class="bold">Power Options</span> </td>
   </tr>
 <tr>
<td><table width="85%" border="0" cellspacing="0" cellpadding="0">
 <tr>
<td class="box2">

<?php 

$query = mysql_query("SELECT * FROM vehicle_poweroptions"); 
    while ( $results[] = mysql_fetch_object ($query));
      array_pop ( $results );
        foreach ( $results as $option ) : ?>

<input name="PO_PowerWindows" type="checkbox" id="PO_PowerWindows" value="<?php echo  $option->id; ?>" />

<?php echo  $option->type; ?><br />

<?php endforeach; ?> 

我该如何实现?

3 个答案:

答案 0 :(得分:3)

Working jsFiddle Demo

您不能拥有多个具有相同ID的元素。您必须更改foreach循环。 我完全删除了id属性。我将使用name属性:

<?php foreach ( $results as $option ) : ?>
    <input
        name="PO_PowerWindows"
        type="checkbox"
        value="<?php echo  $option->id; ?>"
    />
<?php endforeach; ?> 

正如您在代码中看到的,我将id更改为class

这是你的全选复选框(我没有对其进行任何更改):

<input name="PO_ALL" type="checkbox" id="PO_ALL" value="checkbox" onclick="CheckPowerAll()" />

你的功能将是这样的:

function CheckPowerAll() {
    var elements = document.getElementsByName("PO_PowerWindows");
    var l = elements.length;

    if (document.getElementById("PO_ALL").checked) {
        for (var i = 0; i < l; i++) {
            elements[i].checked = true;
        }
    } else {
        for (var i = 0; i < l; i++) {
            elements[i].checked = false;
        }
    }
}

答案 1 :(得分:1)

<input name="PO_PowerWindows[]" type="checkbox" id="PO_PowerWindows" value="<?php echo  $option->id; ?>" checked="checked"/>

答案 2 :(得分:1)

只需添加

array_pop ( $results ); ?>
  <input name="PO_ALL" type="checkbox" id="PO_ALL" value="checkbox" onclick="CheckPowerAll()" />
<?php    foreach ( $results as $option ) : ?>