【问题标题】:Checkbox null means it's not, checkbox checked is 1复选框为空表示不是,复选框选中为 1
【发布时间】:2015-04-21 13:36:58
【问题描述】:

我想拥有它,因此如果复选框为 NULL 或 0,则它不像值为 1 时那样受欢迎。 另外,有没有办法将选中的框限制为 10 个?

当前代码:

if(isset($_POST['submit'])){//to run PHP script on submit
    if(!empty($_POST'favorites')){
    // Loop to store and display values of individual checked checkbox.
        foreach($_POST['favorites[]'] as $selected){
            $query= "UPDATE u_collection SET fav = 0 WHERE username ='".$username."'"; 
            mysqli_query($db,$query);
        }
    } 
}

foreach($gems as $i){
    echo '<tr> 
    <th>'.$i->name.'</th> 
    <th><form action="collection.php" method="post">
    <input type="checkbox"'; 
    if($i -> fav){
        echo 'checked = "checked"';         
    }
    echo 'name="favorites[]" value='.$i->name.'></th></tr></form>'; 
}
?>
<th>
<input type='submit' name='submit' value='Submit'/>
</form>

【问题讨论】:

  • $i -&gt; fav 是字符串吗?您可以在 $gems 循环之外创建一个计数器变量,然后在遇到的每个 if($i -&gt; fav){ 中递增。此外,您的 $username 似乎可能会让您面临 SQL 注入。
  • 对不起,也许我太累了,但我很难理解你的意思(尽管这听起来合乎逻辑!)。你能给我举个例子吗?也许这可以帮助我一点。
  • 你如何获取复选框值,它应该是该行附近的错误if(!empty($_POST'favorites')){ 它必须是if(!empty($_POST['favorites'])){

标签: php mysql arrays checkbox


【解决方案1】:

要检查它是 NULL 还是 0,否则 1 我会使用 empty() 函数

foreach($gems as $i){
    echo '<tr> 
    <th>'.$i->name.'</th> 
    <th><form action="collection.php" method="post">
    <input type="checkbox"'; 
    if(!empty($i->fav)){
        echo ' checked = "checked" ';         
    }
    echo 'name="favorites[]" value='.$i->name.'></th></tr></form>'; 
}

要将选中的框限制为 10,我将使用 javascript (jQuery),如下所示:

<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $('form input[type=checkbox]').on('click', function(){
        if ($('form input[type=checkbox]:checked').length > 10)
        {
           $(this).removeAttr('checked');
           alert('You are only allowed to select 10 checkboxes');
        }
    });
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    相关资源
    最近更新 更多