2010-01-11 90 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

相關問題