如果选中javascript复选框功能将删除不起作用的数据

时间:2012-09-10 15:59:42

标签: javascript checkbox

我在javascript中有一个简单的复选框功能,可以确定检查哪些项目。

<script type="text/javascript" language="javascript">
    var items = new Array();
    function prepareDeleteItems(className){
        var value = className;
        if($('.'+value).attr('checked'))
        {
            items[items.length] = value;
        }
        else
            removeItemFromList(value);
        reAddHiddenInput();
    }

    function reAddHiddenInput(){
        $('.itemsToDelete').html("");
        for(var i = 0; i<items.length; i++)
        {

            $('.itemsToDelete').append('<input type="hidden" name="itemstodelete[]" value="'+($('.'+items[i]).val())+'" />');
        }       
    }

    function removeItemFromList(className){
        for(var i = 0; i<items.length; i++)
        {
            if(items[i] == className)
                items.splice(i,1);
        }
        return;
    }
</script>

然后我有if语句将删除所选项目。

if (isset($_POST['delete'])){

        $delete = $_POST['check'];

            $N = count($delete);
                echo $N;
                    for($i=0; $i < $N; $i++){

                        $strSQL = "DELETE FROM customerinfo ";  
                        $strSQL .="WHERE CUS_ID = '".$delete[$i]."' ";  
                        mysql_query($strSQL);  

                    }
    }

并显示数据

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">

<div>
<input type="button" title="delete item" value='Delete' name='delete'/></div>

<div>

<table width='95%' border='1'  class='hovertable'>
  <tr>
  <td colspan='9'>CUSTOMERS</td>
  </tr>
  <tr>
  <th>---</th>
  <th>---</th>
  <th>ID</th>
  <th>First Name</th>
  <th>Last Name</th>
  <th>Email</th>
  <th>Gender</th>
  <th>Address</th>
  <th>Contact</th>
  </tr>
<?php
while($row = mysql_fetch_array($sql2)){ 

$CUS_ID = $row['CUS_ID'];
$FNAME = $row['FNAME'];
$LNAME = $row['LNAME'];
$EMAIL = $row['EMAIL'];
$GENDER = $row['GENDER'];
$ADDRESS = $row['ADDRESS'];
$CONTACT = $row['CONTACT'];

 ?>
<tr>

<?php if (isset($_POST['update'])){ ?>
<?php if($ID==$CUS_ID){?>

<?php }else{?>

<?php } ?>
<?php }else{?>

    <td align='center'>

现在这是我放置复选框的地方。

<input type="checkbox" name="check[]" class="item_del_<?php echo $CUS_ID; ?>" value="<?php echo $CUS_ID; ?>" onclick="prepareDeleteItems('item_del_<?php echo $CUS_ID; ?>');" />
    <!--ADD-->        </td>                 
<?php } ?>
</form>     

以及更多代码。

但复选框功能不起作用,项目不会被删除。请帮忙。

1 个答案:

答案 0 :(得分:1)

我会做所有的PHP-wise

<input type="checkbox" name="check[]"

可能会成为

<input type="checkbox" name="check[<?php echo $CUS_ID; ?>]"

通过这种方式,您将收到一个数组,其中的项目已被删除且ID为密钥

foreach ($_POST[check] as $key=>$value){
..delete element with id=$key here...
}