![](/img/trans.png)
[英]How to select an HTML element using jQuery or JavaScript and the element's name attribute
[英]How do we change the name of a html select element using javascript and only the tags' name to reference to?
嗨! 我在更改选择元素的名称时遇到问题。 我在页面上生成了约28个选择元素。 这些选择元素均已命名为“下拉列表”。 我使用此名称根据所选选项计算总数。
但是,当我将此信息传递到php页面时,它仅显示最后一个select元素。 为了克服这个问题,我需要在提交时将所有选择标签标记为“ dropdown []”。 这是因为我需要JavaScript的“下拉菜单”才能读取它,而我需要php的“ dropdown []”来处理它。
<select name="dropdown">
<option>
<option>
<option>
</select>
应该更改为:
<select name="dropdown[]">
<option>
<option>
<option>
</select>
最后验证表格。 我该怎么办? 我不将id与名称一起使用,因为我认为这可能会使它变得复杂。
我建议您使用'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();
}
}
我认为您正在错误地解决此问题。 您可能应该使用“ id”来唯一标识元素。 然后,您可以使用许多免费的库之一(jQuery,dojo查询...),为您提供一种从页面中选择元素的更好方法。 通过给您特定的"<select>"
元素类名称,或者仅通过查找页面上的所有“ select”元素即可。
关于名称末尾的“ []”为什么会对您有所帮助,我完全一无所知。 但是我不熟悉php。
使用此框,因为我可以显示代码。
如果我将元素命名为“ 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 []”。
我刚刚找到了您的问题。
为什么仅在您的选择中添加一个id(例如'itsID')标记,然后使用以下标记将其指向更改其名称:
var ref = document.getElementById('itsID');
ref.name = "dropdown[]";
它对我有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.