1

I am trying to make the user check 3 checkboxes from the loop in the php. I don't get any errors but it doesn't limit the number of selection. Jquery

$(document).ready(function() {
    $('.single-checkbox').on('change', function() {
        var noChecked = 0;
        $.each($('.single-checkbox'), function() {
            if ($(this).is(':checked')) {
                noChecked++;
            }
        });
        if (noChecked >= 3) {
            $.each($('.single-checkbox'), function() {
                if ($(this).not(':checked').length == 1) {
                    $(this).attr('disabled', 'disabled');
                }
            });
        } else {
            $('.single-checkbox').removeAttr('disabled');
        };
    });
});

php:

$query="SELECT course.name FROM course";
$results=mysqli_query($dbhandle,$query) or die(mysqli_error($dbhandle));
while ($rows=mysqli_fetch_assoc($results)) {

print("<td><input class='single-checkbox' type='checkbox' id='ch' /></d> <td>".$rows['name']."</td>");

everything is working but the limitation is not working. Thank you in advance.

miken32
  • 42,008
  • 16
  • 111
  • 154
Kim YOOKO
  • 35
  • 1
  • 8
  • 2
    This is nothing to do with PHP. Include the HTML, not the PHP code that created it. You may also want to properly indent your JavaScript so it's easier to read. – miken32 Oct 23 '18 at 23:30

2 Answers2

2

Simply check the number of checked boxes; if it's too high, don't let the box be checked!

$(".single-input").on("change", function() {
    if (this.checked && $(".single-input:checked").length > 3) {
        this.checked=false;
        return false;
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="single-input" /><br/>
<input type="checkbox" class="single-input" /><br/>
<input type="checkbox" class="single-input" /><br/>
<input type="checkbox" class="single-input" /><br/>
<input type="checkbox" class="single-input" /><br/>
<input type="checkbox" class="single-input" /><br/>
miken32
  • 42,008
  • 16
  • 111
  • 154
1

I suggest that you check if JQuery is actually getting the HTML object, in your code you are using $(this), which would be correct, perhaps by the checkbox group you can try for $("#checkboxId") so that the condition of the IF is satisfied and increments its counter variable. See more: Check if checkbox is checked with jQuery