如何在表单提交后动态标记复选框值

时间:2014-11-19 08:23:09

标签: javascript php jquery forms checkbox

即时工作动态复选框和复选框值是从mysql数据库中获取的,复选框值也存储到db表中,表单提交后此处一切正常

问题是,当我点击复选框时,所有复选框值都会被标记并检查但我希望当我点击单个复选框值时,功能是否应该标记或检查已检查的值并且不应标记所有复选框值?

mysql数据库查询

 function select_user_permissions(){

 global $data;

 $result=db_rows(

 "SELECT * FROM `{$data['DbPrefix']}permissions` order by pid");

 return $result;

 }

function select_user_id_permissions(){

global $data;
$adminid=$_REQUEST['userid'];
$result=("SELECT * FROM `{$data['DbPrefix']}user_permission` 
where permuserid='$adminid' ");


return $result;
}



$post['select_user']=select_user_permissions();
$post['select_user_perm']=select_user_id_permissions();


<form name="my_form" method=post>

<? 
foreach($post['select_user'] as $key => $values){
?>
<input type=checkbox name=userperm[] value=<?=$values['pid']?> 
<?php if($post['userperm']) { echo " checked=checked'"; } ?>>

<label for="<?=$values['permname']?>"><?=$values['permname']?></label>
<? } ?>

<input class=submit type=submit name=send value="SAVE CHANGES">
</form>

在这里我得到了解决方案

<script src='http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js'>

<SCRIPT LANGUAGE="JavaScript">

function Check(chk)
{
if(document.myform.Check_ctr.checked==true){
for (i = 0; i < chk.length; i++)
chk[i].checked = true ;
}else{

for (i = 0; i < chk.length; i++)
chk[i].checked = false ;
}
}

// End -->
</script>

<?php
echo "the following values have been checked: ";
$checked="";
$a = array();
if(isset($_POST["userperm"])) {
    foreach($_POST["userperm"] as $j=>$i) {
        $checked .= ($checked==""?"":",") . "checkbox" . $i;
        array_push($a, $i);
    }
}
echo $checked;

function was_checked($i,$a) {
if(in_array($i, $a)===true) {
return "checked='checked'";
return "";
}
}
?>

<? 
foreach($post['select_user'] as $key => $values){

?>
<input type=checkbox name=userperm[] value=<?=$values['pid']?>
<?=was_checked($values['pid'],$a)?>>
<label for="<?=$values['permname']?>"><?=$values['permname']?></label>
<? } ?>

2 个答案:

答案 0 :(得分:0)

你应该创建一个数组 $ arrUserDtls [“userid”] = {user_permission_name}。

而不是

<?php if($post['userperm']) { echo " checked=checked'"; } ?>>

请使用此:

<?php if($arrUserDtls[$values] == $values['permname']) { echo " checked=checked'"; } ?>>

答案 1 :(得分:0)

我不确定逻辑,但在checked=之后你错过了一个单引号

<?php if($post['userperm']) { echo " checked='checked'"; } ?>>

另外,我担心for="<?=$values['permname']?>"将被视为字符串,而不是代码。

<label <?php echo "for='" . $values['permname'] . "'"; ?>><?=$values['permname']?></label>