I’m learning JavaScript right now, quite a task being new to both the syntax and DOM manipulation.
Right now I’m not really using jQuery(or any other library). I’ve used it before but not interested at the moment since I want to get the hang of it then move to a library. I’m looking for plain JavaScript examples that do not involve libraries.
<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>
My goal is to separate both price and quantity (cantidad) and sum them with an “update price” button. It has left me in doubt on how to grab those “price[]” “cantidad[]” inputs and keep them separated, so I can create a loop and well do the math.
Sorry for the spanish/english mix, gets in the way,
You’ll want to use
document.getElementsByNameDocumentation for IE and MDC (Firefox).
And in case you need help with the iteration:
The
+in+prices[i]casts the value to an integer. The|| 0is to make sure that only numbers are returned. Ifprices[i]is a string like “asdf”,+"asdf"evaluate toNaNwhich means thattotalPrice += NaNwould also beNaN. However,NaN || 0evaluates to0, so you can avoid this problem.