Dox The augbey
Dox The augbey

Reputation: 27

Automatic sum field in JavaScript

How to automatically sum some text field without clicking button for sum it?

<tbody>
  <tr>
    <td>
      <div class="form-group">
        <label for="exampleFormControlTextarea1">result
          <a href="JavaScript:value();" class="badge badge-primary">SUM</a>
        </label>
        <input type="text" class="form-control" id="add" name="sum4" readonly>
     </div>
   </td>    
 </tr>
 <tr>
   <td>
    <div class="form-group">
     <label for="exampleFormControlTextarea1">Nilai Akhir/100</label>
      <input type="text" class="form-control" id="addme" name="result4" readonly>
    </div>
  </td>
 </tr>
</tbody>

and this is the JavaScript.

function value()
{
    var input1 = document.getElementById("totalindex1").value;
    var input2 = document.getElementById("totalindex2").value;
    var input3 = document.getElementById("totalindex3").value;
    var result = 0;
    var divider = 100;
    var resdiv = 0;
    result += parseInt(input1) + parseInt(input2) + parseInt(input3);
    resdiv = result / divider;
    document.getElementById('add').value = result;
    document.getElementById('addme').value = resdiv;
}

the variable "totalindex1", "totalindex2", and "totalindex3" already automatically sum for every button checked. I want to make sum for each totalindex as final result without clicking button for sum these variable.

Upvotes: 0

Views: 290

Answers (2)

Jannes Carpentier
Jannes Carpentier

Reputation: 1898

Use the input event on every <input> tag

This event is fired every time the value of the <input> element changes.

You can get all the desired <input> tags by adding a common class name

Example:

function calcsum() {
  let sum = 0;
  for (const inputEl of document.getElementsByClassName("suminput")) {
    sum += +inputEl.value;
  }
  document.getElementById("sum").innerText = sum;
}
<input class="suminput" oninput="calcsum()" />
<input class="suminput" oninput="calcsum()" />
<input class="suminput" oninput="calcsum()" />
<div>Sum: <span id="sum"></span></div>
<br />
<div>The following input will not add to the sum</div>
<input />

Upvotes: 2

Sascha A.
Sascha A.

Reputation: 4616

Create an eventlistener for all inputfields vor sum which calls your value-function.

for (let i=1; i<=3; i++) {
    document.getElementById("totalindex"+i).addEventListener('input', value);
}

Upvotes: 1

Related Questions