Skip to content Skip to sidebar Skip to footer

Counting How Many Checkbox Are Checked Php/html

Hi I am new with php and I was wondering how am i able to count how many 'checkbox' are checked once I click on submit. For example:

Solution 1:

Give the checkboxes names as array like

<input type = "checkbox" value = "box" name = "checkbox[]"/>

And after submit try like

$checked_arr = $_POST['checkbox'];
$count = count($checked_arr);
echo "There are ".$count." checkboxe(s) are checked";

Note : And based on the method that your form submit using...whether it is $_GET or $_POST you need to use $_POST['checkbox'] for POST method and $_GET['checkbox'] for the GET method.


Solution 2:

$checkedBoxes = 0;

// Depending on the action, you set in the form, you have to either choose $_GET or $_POST
if(isset($_GET["checkbox1"])){
  $checkedBoxes++;
}
if(isset($_GET["checkbox2"])){
  $checkedBoxes++;
}
if(isset($_GET["checkbox3"])){
  $checkedBoxes++;
}

Solution 3:

<input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>

to check which boxes have been checked simply traverse through the chk[] array like this:

$chk_array = $_POST['checkbox'];

for($chk_array as $chk_key => $chk_value)
{
print 'Checkbox Id:'. $chk_key . ' Value:'. $chk_value .'is
checked';
}

Solution 4:

You have to rename the names and add values

<input type = "checkbox" value = "box" name = "checkbox[]" value="1"/>
<input type = "checkbox" value = "box" name = "checkbox[]" value="2"/>
<input type = "checkbox" value = "box" name = "checkbox[]" value="3"/>

This way you will know not only number (which you don't actually need)

echo count($_POST['checkbox']);

but also have the actual selected values:

foreach($_POST['checkbox'] as $val)
{
    echo "$val<br>\n";
}

Solution 5:

Using jQuery you can achieve it:

$("input:checkbox:checked").length

This will return the number of checboxes checked.

And in php you'll need to pass it as an array.

echo count($_POST['checkbox']);


Post a Comment for "Counting How Many Checkbox Are Checked Php/html"