php Laravel 4,如何测试复选框是否被选中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20168769/
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
Laravel 4, how to test if a Checkbox is checked?
提问by Brennan Hoeting
I am trying to see if a checkbox is checked or not in my controller. I've read that this is the code to do it
我正在尝试查看控制器中是否选中了复选框。我读过这是执行此操作的代码
if (Input::get('attending_lan', true))
But that returns true even if the checkbox is unchecked.
但即使未选中复选框,它也会返回 true。
采纳答案by Manuel Pedrera
Assuming you have this form code in your view:
假设您的视图中有此表单代码:
// view.blade.php
{{ Form::open() }}
{{ Form::checkbox('attending_lan', 'yes') }}
{{ Form::submit('Send') }}
{{ Form::close() }}
You can get the value of the checkbox like this:
您可以像这样获取复选框的值:
if (Input::get('attending_lan') === 'yes') {
// checked
} else {
// unchecked
}
The key here is that you have to set a value when creating the checkbox in your view (in the example, value would be yes), and then check for that value in your controller.
这里的关键是您必须在视图中创建复选框时设置一个值(在示例中,值为yes),然后在控制器中检查该值。
回答by cen
Use Input::has('attending_lan')
用 Input::has('attending_lan')
Generally speaking, if the checkbox is checked, the request variable will exist. If that is not the case you have a problem somewhere else in the code.
一般来说,如果勾选了复选框,请求变量就会存在。如果不是这种情况,则您在代码中的其他地方有问题。
Also relavant: Does <input type="checkbox" /> only post data if it's checked?
回答by malhal
if(filter_var(Input::get('attending_lan'), FILTER_VALIDATE_BOOLEAN)){
The FILTER_VALIDATE_BOOLEAN filter validates value as a boolean option.
FILTER_VALIDATE_BOOLEAN 过滤器将值验证为布尔选项。
Possible return values:
可能的返回值:
- Returns TRUE for "1", "true", "on" and "yes", and uppercase versions.
- Returns FALSE for "0", "false", "off" and "no", and uppercase versions.
- Returns NULL otherwise.
- 对于“1”、“true”、“on”和“yes”以及大写版本,返回 TRUE 。
- 对于“0”、“false”、“off”和“no”以及大写版本,返回 FALSE 。
- 否则返回 NULL。
source: http://www.w3schools.com/php/filter_validate_boolean.asp
来源:http: //www.w3schools.com/php/filter_validate_boolean.asp
回答by FerBorVa
An alternative is to check the array key to see if it exists, given that when not checked an Input::get('key') might give you problems given its an undefined index in the Input array.
另一种方法是检查数组键以查看它是否存在,因为如果未检查 Input::get('key') 可能会给您带来问题,因为它在 Input 数组中的索引未定义。
$input = Input::all();
if(array_key_exists($input('key',$input)){
// Checked
}else{
// Not Checked
}
Or .. something like that. I'm a bit sloppy but I hope it can help someone.
或类似的东西。我有点马虎,但我希望它可以帮助某人。

