What if JavaScript has different input arrays?

I'm learning JavaScript right now, a completely new task for both syntax and DOM manipulation.

Now I do not use jQuery (or any other library). I used it before, but not interested at the moment, since I want to get it, then go to the library. I am looking for simple JavaScript examples that do not include 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 summarize them using the "update price" button. This left me in doubt about how to capture these inputs "price []" "cantidad []" and leave them separated, so I can create a loop and do the math well.

Sorry for the Spanish / English mix, bothers,

+3
2

document.getElementsByName

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

IE MDC (Firefox).

:

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, .

+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 .

getElementsByName() w3schools.

+2

Source: https://habr.com/ru/post/1728105/


All Articles