计算php/html中选中了多少复选框


counting how many checkbox are checked php/html

嗨,我是php的新手,我想知道点击提交后如何计算检查了多少'checkbox'。例如:

<input type = "checkbox" value = "box" name = "checkbox1"/>
<input type = "checkbox" value = "box" name = "checkbox2"/>
<input type = "checkbox" value = "box" name = "checkbox3"/>

将复选框名称设置为类似的数组

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

并且在提交之后,尝试类似

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

注意:根据您的表单提交使用的方法。。。无论是$_GET还是$_POST,您都需要将$_POST['checkbox']用于POST方法,将$_GET['checkbox']用于GET

$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++;
}
<input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>
<input type = "checkbox" value = "box" name = "checkbox"/>

要检查哪些框已被选中,只需遍历chk[]数组如下:

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

您必须重命名名称并添加值

<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"/>

通过这种方式,你将不仅知道数字(你实际上并不需要)

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

但也有实际选择的值:

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

使用jQuery可以实现它:

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

这将返回已检查的复选框数。

在php中,您需要将其作为数组传递。

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

您可以将复选框的名称设置为数组:

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

然后你会有一个PHP数组($_POST['checkbox']):

echo count( $_POST['checkbox'] ); // this will give you the count

否则,您可以对它们中的每一个进行迭代,并增加一个变量:

$counter = 0;
foreach( array('checkbox1', 'checkbox2', 'checkbox3') as $name ) {
  if( isset( $_POST[ $name ] ) {
     $counter++
  }
}
echo $counter;

当您单击提交时,所有选中的框都将在请求中。在您的情况下,如果选中了checkbox1,则获得:"checkbox1=框"

如果您使用GET作为方法,它将看起来像:http://yoururl.com/yourcode.php?checkbox1=box你可以用$_GET[复选框1']访问它

如果使用POST作为方法,则可以使用$_POST['checkbox1']访问它

您还可以使用isset($_POST['checkbox1'])检查该框是否已选中(以及在请求数据中)