php 如何查看哪个复选框被选中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2268887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I see which checkbox is checked?
提问by Karem
How do I check in PHP whether a checkboxis checked or not?
如何在 PHPcheckbox中检查a 是否被选中?
回答by Tomas Markauskas
If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.
如果复选框被选中,则复选框的值将被传递。否则,该字段不会在 HTTP 帖子中传递。
if (isset($_POST['mycheckbox'])) {
echo "checked!";
}
回答by NullPoiиteя
you can check that by either isset()or empty()(its check explicit isset) weather check box is checked or not
您可以通过isset()或empty()(其检查明确isset)天气复选框是否被选中
for example
例如
<input type='checkbox' name='Mary' value='2' id='checkbox' />
here you can check by
在这里你可以检查
if (isset($_POST['Mary'])) {
echo "checked!";
}
or
或者
if (!empty($_POST['Mary'])) {
echo "checked!";
}
the above will check only one if you want to do for many than you can make an array instead writing separate for all checkbox try like
如果你想为很多做一个,而不是你可以创建一个数组,而不是为所有复选框单独编写,那么上面只会检查一个
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
php
php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo htmlspecialchars($aDoor[$i] ). " ";
}
}
回答by Michael B.
Try this
尝试这个
index.html
索引.html
<form action="form.php" method="post">
Do you like stackoverflow?
<input type="checkbox" name="like" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
form.php
表单.php
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['like']))
{
echo "<h1>You like Stackoverflow.<h1>";
}
else
{
echo "<h1>You don't like Stackoverflow.</h1>";
}
?>
</body>
</html>
Or this
或这个
<?php
if(isset($_POST['like'])) &&
$_POST['like'] == 'Yes')
{
echo "You like Stackoverflow.";
}
else
{
echo "You don't like Stackoverflow.";
}
?>
回答by Can Celik
If you don't know which checkboxes your page has (ex: if you are creating them dynamically) you can simply put a hidden field with the same name and 0 value right above the checkbox.
如果您不知道您的页面有哪些复选框(例如:如果您正在动态创建它们),您可以简单地在复选框上方放置一个具有相同名称和 0 值的隐藏字段。
<input type="hidden" name="foo" value="0" />
<input type="checkbox" name="foo" value="1">
This way you will get 1 or 0 based on whether the checkbox is selected or not.
这样,您将根据是否选中复选框获得 1 或 0。
回答by Omidoo
I love short hands so:
我喜欢短手所以:
$isChecked = isset($_POST['myCheckbox']) ? "yes" : "no";

