简体   繁体   中英

how to count check checkboxes in a specific div JAVASCRIPT

I would like to alert the amount of check boxes that are checked in a specific div (not the ones in the <head> !), here is the code :

HTML

<div class="changer">

<label><input id="mode" type="checkbox" name="mode" value="Mode"        onclick="mode()" />Mode</label><br />

<label><input id="map" type="checkbox" name="map" value="Map" onclick="map()"/>Map</label><br />

<label><input id="joueurs" type="checkbox" name="joueurs" value="Joueurs" onclick="joueurs()" />Joueurs</label><br />

<label><input id="points" type="checkbox" name="points" value="Points" onclick="points()" />Points</label><br />

</div>



</head>

<body>

<div id="text">

</div>

</body>

<button id="send" onclick="send()">Envoyer</button>

Javascript

function joueurs() {
    if((document.getElementById("joueurs").checked == true)) {

            joueursall.style.display = 'inline';
            text.style.display = 'inline';
    }

            else {
                if((document.getElementById("mode").checked == true)) {
                    modeall.style.display = 'none';
                    document.getElementById('mode').checked = false;
                }
                joueursall.style.display = 'none';
                text.style.display = 'none';

            }

        }


document.getElementById("playerlist").addEventListener("change", function() {

var selected = this.value;
document.getElementById("text").innerHTML = "";
var html = '';
for (var i = 0; i < selected; i++) {
html += '<div class="grpjoueur"> <span class="sub-text">Player</span> <label><input type="checkbox" name="botbot" value="BOT"/>BOT</label </div>';
}
  document.getElementById("text").innerHTML = html;
});

Here is the Javascript, it adds 'Joueurs' Dropdownlist if Joueurs is checked and then pop X times something, including a check box, according to the number selected in the Dropdownlist in the #text div

I tried multiple things but always return 0 or all the checkboxes...

In vanilla JS you can use querySelectorAll to query the checkboxes, and then .length to get the number of checkboxes.

var checkboxes = document.querySelectorAll("input[type='checkbox']");
alert(checkboxes.length);

CodePen Demo

If you want to alert only the length of the checked checkboxes, you can query them like this:

var checkedInputs = document.querySelectorAll("input:checked");
alert(checkedInputs.length);

CodePen Demo

  • when you click on the button, it will alert the number of checked boxes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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