Check random checkboxes using JQuery

Issue

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.

I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.

I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.

I am using Jquery.

$(':checkbox:checked').length;

But i want to find the length of all the checkboxes and i want to check 10 random checkbox.

Solution

Are you looking for something like this?

http://jsfiddle.net/qXwD9/

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>

    <script>
        //Creating random numbers from an array
        function getRandomArrayElements(arr, count) {
            var randoms = [], clone = arr.slice(0);
            for (var i = 0, index; i < count; ++i) {
                index = Math.floor(Math.random() * clone.length);
                randoms.push(clone[index]);
                clone[index] = clone.pop();
            }
            return randoms;
        }

        //Dummy array
        function createArray(c) {
            var ar = [];
            for (var i = 0; i < c; i++) {
                ar.push(i);
            }
            return ar;
        }

        //check random checkboxes
        function checkRandom(r, nodeList) {
            for (var i = 0; i < r.length; i++) {
                nodeList.get(r[i]).checked = true;
            }
        }

        //console.log(getRandomArrayElements(a, 10));

        $(function() {

            var chkCount = 100;
            //this can be changed

            var numberOfChecked = 10;
            //this can be changed

            var docFrag = document.createElement("div");

            for (var i = 0; i <= chkCount; i++) {
                var chk = $("<input type='checkbox' />");
                $(docFrag).append(chk);
            }

            $("#chkContainer").append(docFrag);

            $("#btn").click(function(e) {

                var chks = $('input[type=checkbox]');

                chks.attr("checked", false);

                var a = createArray(chkCount);
                var r = getRandomArrayElements(a, numberOfChecked);

                //console.log(r);

                checkRandom(r, chks);
            });

        });
    </script>

</head>
<body>        

    <div id="chkContainer"></div>
    <div>
        <input type="button" id="btn" value="click" />
    </div>

</body>

Answered By – Aneesh

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.