使用 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
相关文章