验证和保留动态复选框的状态 [英] Validating and retaining state of a dynamic checkboxes

查看:111
本文介绍了验证和保留动态复选框的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的php ...我一直在战斗在我的动态复选框,在这样一种方式,如果没有检查形式是返回,还需要保留什么检查时,表单回发由于其他无效的输入。

  $ result = mysql_query(SELECT * FROM course)或die(mysql_error()); 
if($ _ POST ['courses'])和$ _POST [
]
if($ result)
{
while($ row = mysql_fetch_array($ result) 'courses'] == $ row ['cid']){echo $ row ['cid'];}
print< input type = \checkbox\name = ] \value = \$ row [cid] \> $ row [cname] \\\
;
}
}

帮助需要纯粹的PHP代码。提前感谢

解决方案

如果复选框出现在您的php页面的HTML中:

 <?php 

$ checked = isset($ _ POST [checkboxname])? checked:'';
echo< input type ='checkbox'name ='checkboxname'value ='yes'。 $ checked。 >;

?>

表单发布后将保留复选框状态。



更新:



对于您的代码,只需这样做,我认为:

  $ result = mysql_query(SELECT * FROM course)或die(mysql_error()); 
if($ result){
while($ row = mysql_fetch_array($ result)){
$ checked ='';
/ * ERROR:if(isset($ _ POST ['courses'])和$ _POST ['courses'] == $ row ['cid']){* /
if(isset _POST ['courses']){
if(in_array($ row ['cid'],$ _POST ['courses']){
echo $ row ['cid'];
$ checked =checked;
}
}
echo< input type = \checkbox\name = \courses [] \value = \ $ row [cid] \。$ checked。> $ row ['cname'] \\\
;
}
}



编辑:条件也需要改变,我想,正如上面的代码所示。


Am new to php... I have been battling on my dynamic checkboxes in such a way that if none is checked the form is return, also I need to retain what was checked when the form postback due to other invalid inputs.

$result = mysql_query("SELECT * FROM course") or die(mysql_error()); 
if ($result) 
{ 
  while ($row = mysql_fetch_array($result)){
    if (isset($_POST['courses']) and $_POST['courses'] == $row['cid']) {echo $row['cid'];} 
    print "<input type=\"checkbox\" name=\"courses[]\" value=\"$row[cid]\">$row[cname]\n"; 
  }
}

Help needed purely on php codes. Thanks in advance

解决方案

Do this where the checkbox appears in the HTML on your php page:

<?php

   $checked = isset($_POST["checkboxname"]) ? " checked" : '' ;
   echo "<input type='checkbox' name='checkboxname' value='yes'" . $checked . ">";

?>

This will retain the checkbox state after the form has been posted.

UPDATE:

For your code, just do it like this, I think:

$result = mysql_query("SELECT * FROM course") or die(mysql_error()); 
if ($result) {
    while ($row = mysql_fetch_array($result)) {
        $checked = '';
/* ERROR:  if (isset($_POST['courses']) and $_POST['courses'] == $row['cid']) { */
        if (isset($_POST['courses']) {
           if (in_array($row['cid'], $_POST['courses']) {
               echo $row['cid'];
               $checked = " checked";
           }
        }
        echo "<input type=\"checkbox\" name=\"courses[]\"  value=\"$row[cid]\"" . $checked . ">$row['cname']\n"; 
    }
}

EDIT: The condition needs to change too, I think, as I show in the code above.

这篇关于验证和保留动态复选框的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆