javascriptjquerydividewarehouse

How to Divide 1 value from input box to 10 another input box divided by 10 without rounding


I am making a form to input Products to warehouse, So, the condition that i want is:

When I type and enter a value in Quantity box (Blue circle), I want that value shown to another 10 input boxes pallet list (red circle), But it has to be 69 Pcs in each box ( 69 is only total that actually fit on the pallet in real warehouse ) and if it still have rest, put the last rest in the last box. This is the illustration that might help :

enter image description here

Say, I have produce 630 PCS items, and when I put 630 to the Quantity Box, It should be shown 69 PCS in every pallet list, 69 until it cannot be divided again. The rest of the divide, have to be placed on the last box.

Example :

Quantity : 630 PCS

Pallet 1: 69

Pallet 2: 69

Pallet 3: 69

Pallet 4: 69

Pallet 5: 69

Pallet 6: 69

Pallet 7: 69

Pallet 8: 69

Pallet 9: 69

Pallet 10: 9 (The rest have to be on the last pallet)

Can someone help me? Thank you, Terima Kasih.


Solution

  • You want the modulo operation and the integer division. The % operator in JavaScript works fine as modulo on positive numbers. You do not need correct modulo operations on negative numbers for this particular problem. The integer division is a floored normal division. The Math object provides a floor method.

    var
      byId     = document.getElementById.bind(document),
      intVal   = id => parseInt(byId(id).value),
      onChange = ev =>
      {
        let
          qty  = intVal('quantity'),
          ppb  = intVal('peaces-per-box'),
          rest = qty % ppb,
          html = ''
        ;
        if(!qty || !ppb)
          return byId('pallets').innerHTML = '';
    
        for (var c = Math.floor(qty / ppb), i = 0; i < c; i++)
          html += `<div></div><lable for="pallet-${i}"></lable> <input id="pallet-${i}" value="${ppb}"></div>\n`;
        if(rest)
          html += `<div></div><lable for="pallet-${i}"></lable> <input id="pallet-${i}" value="${rest}"><div></div>\n`;
        byId('pallets').innerHTML = html;
      }
    ;
    byId('quantity'      ).addEventListener('change', onChange);
    byId('peaces-per-box').addEventListener('change', onChange);
    onChange();
    <!DOCTYPE html>
    <head>
      <meta charset="UTF-8">
      <title>Quantities</title>
    
    <body>
      <form>
        <div>
          <lable for="quantity">quantity</lable>
          <input id="quantity" type="number" min="0" step="1" placeholder="enter quantity">
        </div>
        <div>
          <lable for="peaces-per-box">peaces per box</lable>
          <input id="peaces-per-box" type="number" min="1" step="1" placeholder="enter max. peaces per box">
          <div id="pallets">
          </div>
        </div>
      </form>