嗨!我在更改select元素的名称时遇到问题。我在页面上生成了大约28个选择元素。这些选择元素中的每一个都被命名为"dropdown“。我使用此名称根据所选的选项来计算总数。
但是当我把这个信息传递给一个php页面时,它只显示最后一个select元素。为了克服这个问题,我需要在提交时将所有的选择标记标记为"dropdown[]“。这是因为我需要"dropdown“让javascript读取它,我需要"dropdown[]”让php来处理它。
<select name="dropdown">
<option>
<option>
<option>
</select>应更改为:
<select name="dropdown[]">
<option>
<option>
<option>
</select>最后对表单进行验证。我该怎么做呢?我不会将it与名称一起使用,因为我认为这可能会使它变得复杂。
发布于 2009-08-29 05:00:21
我建议您保留'dropdown[]‘名称,然后您可以使用getElementsByName函数,该函数将返回一个可迭代的数组,其中包含文档中具有给定名称的元素:
var dropdownArray = document.getElementsByName('dropdown[]'),
i, element, n = dropdownArray.length;
for (i = 0; i < n; i++) {
element = dropdownArray[i];
// you can check the value of each element here...
}编辑:修改代码:
function addup(){
var tot = 0, i, // i declaration was missing
dropdowns = document.payment.elements['dropdown[]'];
for(i = 0;i<dropdowns.length;i++) {
//alert(i);
var find = dropdowns[i];
var check = find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay') {
// not using eval anymore
var tot1 = document.payment.elements[check.substring(4)+'_amount'].value;
//alert(tot1);
tot += +tot1; // unary plus operator to convert to number
}
document.payment.total_amount.value=tot;
calcTotal();
}
}发布于 2009-08-29 05:06:26
我认为你处理这个问题是错误的。您可能应该使用"id“来唯一地标识元素。然后,您可以使用许多免费的库中的一个(jQuery、dojo query……)为您提供一种从页面中选择元素的更好方法。或者给出特定的"<select>"元素类名,或者直接在页面上查找所有的"select“元素。
我完全不知道为什么名字末尾的"[]“会对你有影响。但是我不熟悉php。
发布于 2009-08-29 05:12:29
使用这个框是因为我可以显示代码。
如果我将元素命名为"dropdown[]“,我会得到一个错误,如本例所示:
function addup(){
var tot=0;
for(i=0;i<(document.payment.dropdown.length);i++)
{
//alert(i);
var find=document.payment.dropdown[][i];
var check=find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay')
{
var other="document.payment."+check.substring(4)+"_amount.value";
var tot1=eval(other);
//alert(tot1);
tot+=parseInt(tot1);
}
document.payment.total_amount.value=tot;
calcTotal();
}
}请原谅我简陋的代码,但是如果我将它命名为"dropdown[]“,这似乎不起作用。因此,我需要名称在开始时是"dropdown“,然后在提交时应该更改为"dropdown[]”。
https://stackoverflow.com/questions/1350495
复制相似问题