Home > Software engineering >  JQuery randomly check checkboxes in a column of datatable in a html page
JQuery randomly check checkboxes in a column of datatable in a html page

Time:06-26

I have a datatable with a column of checkboxes. Upon pressing a button a code needs to identify how many unchecked checkboxes are there and then randomly tick them based on the requirement (from a textbox by name quantity).

What I have tried is using the code below:

$(document).ready(function() {
        $('#btnRand').click(function(){
        var checkboxes = $("input.selectQuestion:checkbox").length;
        var must_check = 2; //supposed to come from input box by name quantity
    while ($("input.selectQuestion:checkbox:checked").length < must_check) {
                // Pick random checkbox
                var random_checkbox = Math.floor(Math.random() * checkboxes)   1;
                // Check it
                $("input.selectQuestion:checkbox:nth-child(" random_checkbox ")").prop("checked", true);
            }
        
        })
        });

But unfortunately its not working as expected (checkboxes are not checked upon clicking the btnRand). Could someone help to fix this?

Here is the jsfiddle: https://jsfiddle.net/ab9sej5p/5/

CodePudding user response:

Your table wire-up was throwing a Script error.

$(document).ready( function() {
  var table = $('#example').DataTable({
   ....

which were preventing the

$('#btnRand').click(function(){

from running also the while loop seems to get stuck in an infinite loop and the

input.selectQuestion:checkbox:nth-child

seemed to reference the wrong thing, probably because it was a js fiddle example. Rather than use the datatable to add the class select question dynamically, why not put it on the check box's in the HTML, I decided to simplify it, so I tripped it back and thew something together:

https://jsfiddle.net/kve184pt/

As there are only 3 rows it may seam like its not random but it is, just occashonly keeps picking the same random item(s) a few times in a row

I hope this help

  • Related