Maydha Mn Maydha Mn - 6 months ago 32
MySQL Question

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, i.e. if I want only 3 out of 5 boxes checked off how can I do that in 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. 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). 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

$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();


?>

Answer

Like @Shadouts said, you can't control the checkboxes from PHP, you need Javascript. To create the list, echo the output of the query like you do inside the html tags. 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.

So now our checkboxes can be seen in the browser. What's left is to control them. We will do that with 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. It means we select some html elements either by class, id or something else. To select elements by class, .+className. To select elements by their 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
  2. $('#checkboxes input:checked').each: For each checkbox that has been checked, we increment the count value by one.
  3. If the user has checked 3 checkboxes then disable ( $(this).attr("disabled", true); ) all the unchecked ( $('#checkboxes input:not(:checked)').each ) checkboxes.
  4. If not, enable them: $(this).removeAttr('disabled');

In order for you to use PHP inside the html tags, the file needs to be .php. So the file - let's say checkbox.php - would be like this:

<!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.

Comments