2010-01-11 93 views
3

我现在正在学习JavaScript,这对于语法和DOM操作来说都是新的任务。当JavaScript中有不同的输入数组时,该怎么办?

现在我没有真正使用jQuery(或任何其他库)。我之前使用过它,但目前没有兴趣,因为我想获得它的诀窍,然后转到图书馆。我正在寻找不涉及库的普通JavaScript示例。

<form name="carritoDeCompras" action=""> 
<table width="100%" border="0"> 
    <tr> 
    <td width="17%">Nombre de Articulo </td> 
    <td width="22%">Precio</td> 
    <td width="51%"> Cantidades</td> 
    </tr> 
    <tr> 
    <td>Desktop</td> 
    <td><input name="price[]" type="text" disabled="disabled" value="1900.00" id="1 "/></td> 
    <td><input name="cantidad[]" type="text" value="4" id="1 cantidad" /></td> 
    </tr> 
    <tr> 
    <td>Monitor</td> 
    <td><input name="price[]" type="text" disabled="disabled" value="322.00" id="2" /></td> 
    <td><input name="cantidad[]" type="text" value="2" id="2 cantidad" /></td> 

    </tr> 
    <tr> 
    <td>Disco Duro</td> 
    <td><input name="price[]" type="text" disabled="disabled" value="244.33" id="3"/></td> 
    <td><input name="cantidad[]" type="text" value="10" id="3 cantidad" /></td> 
    </tr> 
    <tr> 
    <td>Mouse</td> 
    <td><input name="price[]" type="text" disabled="disabled" value="100.21" id="4"/></td> 
    <td><input name="cantidad[]" type="text" value="100" id="4 cantidad" /></td> 
    </tr> 
</table> 
</form> 

我的目标是价格和数量(cantidad)分离,并与“更新价格”按钮,总结他们。它让我不确定如何抓住这些“价格[]”“cantidad []”输入并将它们分开,这样我就可以创建一个循环并很好地进行数学运算。

对不起,西班牙文/英文混合,得到的方式,

+0

+1想要没有图书馆的学习! – 2010-01-11 22:27:51

回答

2

你要使用document.getElementsByName

var prices = document.getElementsByName("price[]"); 
var quantities = document.getElementsByName("cantidad[]"); 

的文档IEMDC(火狐)。

而且在您需要的迭代帮助的情况下:

var totalPrice = 0, 
    totalQuantity = 0, 
    i; 

i = prices.length; 
while (i--) { totalPrice += +prices[i]  || 0; } 

i = quantities.length; 
while (i--) { totalQuantity += +quantities[i] || 0; } 

+prices[i]+铸就价值为整数。 || 0是为了确保只有数字被返回。如果prices[i]是类似“asdf”的字符串,则+"asdf"评估为NaN,这意味着totalPrice += NaN也将是NaN。然而,NaN || 0评估为0,所以你可以避免这个问题。

+0

Gah,我非常接近答案,但是因为我已经看了这个问题已经有一个小时了,所以它已经变得令人沮丧= /。非常感谢,你真的让我的“+ = +价格[我] || 0;”让我疑惑。 我现在可以处理迭代,因为物品的价格必须与数量的ID(和物品的ID相匹配,因此我可以乘以物品)。 最后一个问题,为什么有“object.text(来自一个例子),或object.data,object.innerHTML。object.value”并且不同于Node的值? – allenskd 2010-01-11 22:53:52

+0

你从哪里得到'object'? 'value'将被定义为'form'元素,比如'input','select'和'textarea'。 'innerHTML'通常在大多数元素上定义,并且是该标记内部所有内容的字符串表示形式。这里有一个很好的参考:https://developer.mozilla.org/en/DOM/element – 2010-01-12 00:41:12

2

您可以使用名为getElementsByName()的方法。例如:

var inputs = document.getElementsByName("cantidad[]"); 
var total = 0; 
for (var i = 0; i < inputs.length; i++) { 
    total += inputs[i].value - 0; // the - 0 is there to make sure the value is converted to a number 
} 

total变量现在包含总量。

Documentation on getElementsByName() at w3schools

+0

你错过了你是增量器 – 2010-01-11 22:29:22

+0

所以我是,我赶紧写了它:) – 2010-01-11 22:30:39

相关问题