简体   繁体   中英

Count checked checkboxes

I am new to HTML, I have a list of checkboxes on a form in an HTML page.

Each checkbox on each line represents a different category "I" "D" "C" and "S".

Part of my code is as follows:

<form>
    1.<input type="checkbox" name="Personality_1.1" value="I"/>Animated &nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_1.2" value="D" />Adventurous &nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_1.3" value="C" />Analytical &nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_1.4" value="S" />Adaptable<br /><br />

    2.<input type="checkbox" name="Personality_2.1" value="I"/>Playful&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_2.2" value="D" />Persuasive&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_2.3" value="C" />Persistent&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_2.4" value="S" />Peaceful<br /><br />

    3.<input type="checkbox" name="Personality_3.1" value="I"/>Sociable&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_3.2" value="D" />Strong Willed&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_3.3" value="C" />Self-sacraficing&nbsp;&nbsp;&nbsp;&nbsp
    <input type="checkbox" name="Personality_3.4" value="S" />Submissive<br /><br />

I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted.

Such a: "Five D's have been checked" "Three C's have been checked"

Is there a way I can do this with Javascript or PHP? If so can anyone help direct me to figure out how to do so?

Well, with PHP, assuming your submitting the form with POST:

$counts = array_count_values($_POST);

And you'll get an associative array with the values as keys and counts as values. So if for example 3 D 's have been checked, $counts['D'] will hold "3".

As an example, you can use something like this:

window.onload = function () {
    document.getElementById("btn1").onclick = function () {
        var allChk = document.getElementsByTagName("input"),
            counts = {},
            i, j, cur, val;
        for (i = 0, j = allChk.length; i < j; i++) {
            cur = allChk[i];
            if (cur.type === "checkbox") {
                if (!(cur.value in counts)) {
                    counts[cur.value] = 0;
                }
                if (cur.checked) {
                    counts[cur.value]++;
                }
            }
        }

        for (val in counts) {
            console.log("There are " + counts[val] + " " + val + "'s checked");
        }
    };
};

DEMO: http://jsfiddle.net/Dwjez/1/

Click the button, after checking some checkboxes, and look at your console to see the results. It just finds all checkboxes, and stores the number of checked ones, per value, in an object literal...then the final loop is there just to print the results in the console.

This was just a simple example with event handling, but I'd suggest looking at addEventListener vs onclick to see another way to handle events (with addEventListener ).

jquery-:

var numberOfCheckboxesSelected = $('input[type=checkbox]:checked').length;

javascript--:

var checkboxLength = document.forms["formName"].elements["checkbox[]"].length;
var checkboxes = document.forms["formName"].elements["checkbox[]"];


for(var i = 0; i < checkboxLength; ++i) {
   if(checkboxes[i].checked) {
      // do stuff
   }
}

how about...

var getCount = function(type) {
  return document.querySelectorAll('input[value='+type+']:checked').length;
}
alert(getCount('A') + "As have been selected");

and it looks like you would be better off using a radio group instead of checkboxes. From looking at your html, do you want the user to be able to select more than one item in each section?

Here is the code you want. Try it and let me know.

<HTML>
<HEAD>
<TITLE>Document Title</TITLE>
</HEAD>
<BODY>

<FORM NAME="f1" action="next_page.php" method="post">
<input type="checkbox" name="chkGuar[]" value="mike">&nbsp;Mike<br />
<input type="checkbox" name="chkGuar[]" value="joy">&nbsp;Joy<br />
<input type="checkbox" name="chkGuar[]" value="harry">&nbsp;harry<br />
<input type="checkbox" name="chkGuar[]" value="watson">&nbsp;watson<br />
<input type="checkbox" name="chkGuar[]" value="george">&nbsp;george<br />
<input type="checkbox" name="chkGuar[]" value="peter">&nbsp;Peter<br />
<input type="submit" name="chksbmt" value="Send" />
<!-- <div id="myrow" style="visibility:hidden">
<input type = text name ='txtGRTNo' tabindex = 19 size="20">
</div>
<div width="338" align="left" colspan="3" height="12"></div> !-->
</FORM>

</BODY>
</HTML>

next_page.php

<?php
if(isset($_POST['chksbmt'])){
    $counts = count($_POST['chkGuar']);
    echo "this is the next page. you checked $counts checkbox <br /><br />";
    for($i=1;$i<=$counts;$i++){
    echo "<input type='text' style='border:1px solid #000;' value='your text box here' /><br/><br/>";
    }
}

You should write your form code like this:

<form>
    1.<input type="checkbox" name="chkI[]" value="I1"/>Animated 
    <input type="checkbox" name="chkD[]" value="D1" />Adventurous 
    <input type="checkbox" name="chkC[]" value="C1" />Analytical 
    <input type="checkbox" name="chkS[]" value="S1" />Adaptable

    2.<input type="checkbox" name="chkI[]" value="I2"/>Playful
    <input type="checkbox" name="chkD[]" value="D2" />Persuasive
    <input type="checkbox" name="chkC[]" value="C2" />Persistent
    <input type="checkbox" name="chkS[]" value="S2" />Peaceful

    3.<input type="checkbox" name="chkI[]" value="I3"/>Sociable
    <input type="checkbox" name="chkD[]" value="D3" />Strong Willed
    <input type="checkbox" name="chkC[]" value="C3" />Self-sacraficing
    <input type="checkbox" name="chkS[]" value="S3" />Submissive
</form>

Look at the "name" and "value" attributes. I made I change to the values of them.

You say:

I need to find out how many value "I" checkboxes have been checked, how many value "D" checkboxes have been checked, and so on, and then display the total of each category when the form is submitted .

If you make a submit...

<?php

if(!empty($_GET['chkD'])) {
    $counterChkD = 0;
    foreach ($_GET['chkD'] as $chkD){
        echo $chkD."\n";
        //echoes the value set in the HTML form for each checked checkbox associated with the "D" value
        //so, if I were to check "Adventurous", "Persuasive", and "Strong Willed" it would echo value D1, value D2, value D3.
        $counterChkD++;
    }
    echo "# of 'D-CheckBoxes' checked: ".$counterChkD."\n";
}

?>

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