Frankie
Frankie

Reputation: 499

Javascript - Add rows and sum values in field

I have a form with this filed and by button I can add rows: book_desc[], book_pages[]. The field for sum of books_pages[] is book_pages_tot. With my javascript I want to add rows with value in each book_pages field and sum this values in a book_pages_tot field there are the total values.

This is the script: the form and fields

<form method="POST" action="addpages.php" name="books" onmouseover="javascript:sum();">

<button type="button" onClick="addRow('dataTable')">  Add pages </button>
    <table id="dataTable" class="form">
        <input type="text" class="form-control" name="book_pages[]"  onblur="javascript:sum();">
        <input type="text" class="form-control" name="book_pages_total"  onblur="javascript:sum();">
    </table>
</form>

The javascript:

<script language="javascript">
    function sum() {
        var a = parseInt(document.books.book_pages[].value);
        var result = a +a[];
    document.books.tot_prestazioni_A.value = result;
}       
</script>

This script not work. How to sum the values put in each book_pages[] in the book_pages_tot filed?

I hope to explain my problem.

Thanks

Upvotes: 1

Views: 2759

Answers (2)

zer00ne
zer00ne

Reputation: 43860

Nothing made any sense so I rewrote the whole thing. The action is to a real test server, but it won't submit in SO due to security restrictions, but it will submit if you use it on your own. Details are commented in the Snippet.

SNIPPET

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
  <title>00A00</title>
  <style>
    button,
    input {
      font: inherit;
    }
    .pages {
      width: 6ch;
    }
  </style>
</head>

<body>
    <form method="post" action="http://httpbin.org/post" name="books">
      <button type="button" onClick="addRow()">Add Book</button>
      <table id='dataTable'>
        <tbody id='dataMain'>
          <tr id='original' class='row'>
            <td>
              <input class='book' placeholder='Enter Title'>
            </td>
            <td>
              <input type="number" class="form-control pages" name="pages" min='1' max='9999' value='1' oninput='totalPgs();'>
            </td>
          </tr>
        </tbody>
        <tbody>
          <tr id='dataTotal'>
            <td>
              <input type='submit'>
            </td>
            <td>
              <output id='total' class="form-control" name="total"></output>
            </td>
          </tr>
        </tbody>
      </table>
    </form>
  <script>
    function addRow() {
      // Reference the first <tr> as row
      var row = document.getElementById('original');
      // Reference the first <tbody> as main
      var main = document.getElementById('dataMain');
      // Clone row
      var clone = row.cloneNode(true);
      // Remove clone's id
      clone.removeAttribute('id');
      // Clean clone of any data
      clone.querySelectorAll('input').forEach(function(inp) {
        inp.value = ''
      });
      // Append clone as the last child of main
      main.appendChild(clone);
    }

    function totalPgs() {
      // Reference the <output> as out 
      var out = document.getElementById('total');
      // Collect all nodes with class .pages into a NodeList called pgs
      var pgs = document.querySelectorAll('.pages');

        /* Array called arr is made by...
	|| ...map.call pgs NodeList on each node called pg...
	|| ...convert each pg value to a true number...
	|| ...return all number values as an array called arr
	*/
      var arr = Array.prototype.map.call(pgs, function(pg) {
        var cnt = parseInt(pg.value, 10);
        return cnt;
      });
      // .apply the function sum() to array called arr
      var total = sum.apply(sum, arr);
      // The value of out is whatever total is
      out.value = total;
      // return the value of total
      return total;
    }

    /* sum() will take any amount of numbers and add...
    || ...them up. Works best with .apply() or .call()
    || Usage: 
    || var totalNumber = sum.apply(sum, array);
    || or
    || var totalNumber = sum.call(sum, object);
    */
    function sum() {
      var res = 0;
      var i = 0;
      var qty = arguments.length;
      while (i < qty) {
        res += arguments[i];
        i++;
      }
      return res;
    }
  </script>
</body>

</html>

Upvotes: 1

talkhabi
talkhabi

Reputation: 2759

Use this function :

function sum() {
    var inputs = document.books["book_pages[]"],
        result = 0;

    for(var i in inputs){

        var input = inputs[i],
            val   = input.value;
        if(val !== undefined && val !== '')
            result += parseInt(val);
    }
    document.books.tot_prestazioni_A.value = result;
} 

Demo

Upvotes: 0

Related Questions