問題描述
我有一個帶有如下復選框的表單:
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 時,在復選框名稱中使用括號?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!