简体   繁体   English

如何限制直接从MYSQL数据库和PHP创建的清单中的选择(*不通过在HTML中手动创建清单)

[英]How to Limit selection in checklist created directly from MYSQL database and PHP (*Not by manually making a checklist in HTML*)

My code so far outputs data from mysql table on a website as a checklist, but I am having trouble setting a limit to how many options can be checked off, ie if I want only 3 out of 5 boxes checked off how can I do that in php? 到目前为止,我的代码从网站上的mysql表中输出数据作为清单,但是我无法设置可以检查的选项数量的限制,即如果我只希望5个复选框中的3个被选中,我该怎么做在PHP中?

NOTE: Most of the answers out there for checkbox limit show examples where a checklist has been manually created in HTML and then using Javascript a limit is put on the number of boxes that can be checked off. 注意:关于复选框限制的大多数答案都显示了一些示例,这些示例中已经用HTML手动创建了一个清单,然后使用Javascript对可以选中的框数进行了限制。 However, this is not the case in my code; 但是,我的代码中不是这种情况。 my code outputs a checklist that is not manually created in HTML but is automatically created from a pre-set MYSQL database using PHP (as shown below). 我的代码输出的清单不是使用HTML手动创建的,而是使用PHP从预设的MySQL数据库自动创建的(如下所示)。 How can I put a limit to the boxes checked off in this case? 在这种情况下,如何限制已选中的框? Solution/Examples with code would be greatly appreciated! 带有代码的解决方案/示例将不胜感激!

Here is my PHP code: 这是我的PHP代码:

<?php

    $username = "root";
    $password = "";
    $hostname = "localhost";

    $dbname = "major_degrees";
    $str='';

    // Create connection
    $conn = new mysqli($hostname, $username, $password, $dbname);

    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

    $sql = "SELECT degree_name FROM majors";
    $result = $conn->query($sql);

    $out = '';
    $cnt = 0;
    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $cnt++;
            $out .= '<input id="cb_' .$cnt. '" class="someclass" type="checkbox" />' .$row['degree_name']. '<br/>';
        }
        echo $out;
    } 
    $conn->close();


?>

You cannot control what a user is doing client-side without using JavaScript as it is the programming language that controls the client-side browser experience. 如果不使用JavaScript,就无法控制用户在客户端所做的事情,因为它是控制客户端浏览器体验的编程语言。 PHP is generating the HTML server side and then printing it, but there is no back-and-forth between what a user is doing on their side and the server. PHP正在生成HTML服务器端,然后进行打印,但是用户在自己的端与服务器之间没有来回的动作。

What you can do is generate the list by PHP and then use JavaScript to control the list. 您可以做的是通过PHP生成列表,然后使用JavaScript控制列表。 The JavaScript must be read by the browser after the PHP output (or more correctly, after the list has been generated) for it to work properly. 浏览器必须在PHP输出之后(或更正确地,在生成列表之后)读取浏览器,以使其正常工作。 You could output the JavaScript from the PHP, or better yet, use JavaScript AJAX to call the PHP list and then associate controllers. 您可以从PHP输出JavaScript,或者更好的方法是,使用JavaScript AJAX调用PHP列表,然后关联控制器。

Like @Shadouts said, you can't control the checkboxes from PHP, you need Javascript. 就像@Shadouts所说的那样,您无法通过PHP控制复选框,需要Javascript。 To create the list, echo the output of the query like you do inside the html tags. 要创建列表,请像在html标记内一样显查询的输出。 For the sake of the example I won't include what the query returns for the checkboxes, but simple incremental data. 在本示例中,我将不包括查询为复选框返回的内容,而是简单的增量数据。

<form action="some_file" method="">
    <div id="checkboxes">
    <?php
        for($i = 0; $i < 8; $i++) {
            echo "<input class='checkChange' type='checkbox' name='check' value='ch".($i+1)."'>check ".($i+1)."<br>";
        }
    ?>
    </div>

    <input type="submit" value="Submit">
</form>

This creates 8 simple checkboxes (in your case, checkboxes, each with the appropriate value and text. A better way, would be to fill the checkbox list with AJAX, but since it seems like you are new to these technologies, I'll try and keep it as simple as possible. 这将创建8个简单的复选框(以您为例,每个复选框具有适当的值和文本。一种更好的方法是用AJAX填充复选框列表,但是由于您似乎不熟悉这些技术,因此我将尝试并使其尽可能简单。

So now our checkboxes can be seen in the browser. 因此,现在可以在浏览器中看到我们的复选框。 What's left is to control them. 剩下的就是控制它们。 We will do that with jQuery. 我们将使用jQuery来实现。

In some script tags we have the following: 在某些脚本标签中,我们具有以下内容:

$('.checkChange').change(function() {
    var count = 0;

    $('#checkboxes input:checked').each(function() {
        count++;
    });

    if (count >= 3) {
        $('#checkboxes input:not(:checked)').each(function() {
            $(this).attr("disabled", true);
        });
    } else {
        $('#checkboxes input:not(:checked)').each(function() {
            $(this).removeAttr('disabled');
        });
    }
});

Just to let you know, things like $('.checkChange') are jQuery Selectors. 只是让您知道,像$('.checkChange')这样的东西就是jQuery Selectors。 It means we select some html elements either by class, id or something else. 这意味着我们通过类,id或其他方式选择一些html元素。 To select elements by class, . 要按类别选择元素, . +className. + className。 To select elements by their ID # +ID. 通过其ID # + ID选择元素。 Let's decode the above code sample now: 让我们现在解码以上代码示例:

  1. First, whenever a checkbox is clicked (or more accurately changes), the .change function is called: $('.checkChange').change 首先,每当单击复选框(或更准确地说是更改)时, .change函数就会被调用: $('.checkChange').change
  2. $('#checkboxes input:checked').each : For each checkbox that has been checked, we increment the count value by one. $('#checkboxes input:checked').each :对于每个已选中的复选框,我们将计数值加一。
  3. If the user has checked 3 checkboxes then disable ( $(this).attr("disabled", true); ) all the unchecked ( $('#checkboxes input:not(:checked)').each ) checkboxes. 如果用户已选中3个复选框,则禁用( $(this).attr("disabled", true); )所有未选中的( $('#checkboxes input:not(:checked)').each )复选框。
  4. If not, enable them: $(this).removeAttr('disabled'); 如果没有,请启用它们: $(this).removeAttr('disabled');

In order for you to use PHP inside the html tags, the file needs to be .php . 为了使您可以在html标记内使用PHP,文件必须为.php So the file - let's say checkbox.php - would be like this: 因此,文件-例如checkbox.php-将如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Checkboxing</title>
</head>
<body>

<form action="action.php" method="post">
    <div id="checkboxes">
    <?php
        for($i = 0; $i < 8; $i++) {
            echo "<input class='checkChange' type='checkbox' name='check' value='ch".($i+1)."'>check ".($i+1)."<br>";
        }
    ?>
    </div>

    <input type="submit" value="Submit">
</form>

</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
    $('.checkChange').change(function() {
        var count = 0;

        $('#checkboxes input:checked').each(function() {
            count++;
        });

        if (count >= 3) {
            $('#checkboxes input:not(:checked)').each(function() {
                $(this).attr("disabled", true);
            });
        } else {
            $('#checkboxes input:not(:checked)').each(function() {
                $(this).removeAttr('disabled');
            });
        }
    });
</script>
</html>

To see the exact functionality I described above, check out this fiddle I created. 要查看我上面描述的确切功能,请查看我创建的这个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM