use brackets in checkbox name when using php and javascript?(使用 php 和 javascript 时,在复选框名称中使用括号?)
问题描述
我有一个带有如下复选框的表单:
i have a form with checkboxes like this:
<input type="checkbox" name="type[]" value="1" />Fast Food<br>
<input type="checkbox" name="type[]" value="2" />Table Service<br>
<input type="checkbox" name="type[]" value="3" />Cafeteria<br>
当我在名称中使用方括号 (type[]) 时,我的 php 工作:
when i use the brackets in the name (type[]), my php works:
$type=$_POST['type'];
echo "types are:";
for ( $counter = 0; $counter < sizeof($type); $counter += 1) {
echo "<br>".$type[$counter];
}
但我的 javascript 不起作用:
but my javascript doesn't work:
var f = document.addform;
for (var i=0;i<f.type.length;i++){
if(f.type[i].checked==true){
break;
}
if(i==(f.type.length-1)){
alert("No categories entered!");
valid=false;
}
}
但是,如果我去掉括号:
however, if i take away the brackets:
<input type="checkbox" name="type" value="1" />Fast Food<br>
然后 PHP 不起作用,但 javascript 起作用.
then the PHP doesn't work but the javascript does.
这是怎么回事?我应该用什么?
what's going on here? what should i use?
谢谢.
推荐答案
PHP 有一个不同寻常的系统来处理多个具有相同名称的表单控件,它期望名称包含 []
但它没有不要在变量名中使用它们.
PHP has an unusual system for handling multiple form controls with the same name, it expects the names to include []
but it doesn't use them in the variable name.
JavaScript 没有这个问题.该属性仍将包含括号.
JavaScript doesn't have that issue. The property will still have the brackets.
当然,方括号在JS中是有特殊意义的,所以不能用点号来访问属性.
Of course, square brackets have special meaning in JS, so you can't use dot notation to access the property.
f['type[]'][i].checked
这篇关于使用 php 和 javascript 时,在复选框名称中使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 php 和 javascript 时,在复选框名称中使用括号


- Laravel 仓库 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01