DoN_Dan
DoN_Dan

Reputation: 69

Adding HTML form using JavaScript to get a total in text box

So for the final piece of my code, I need to add all the form values together and show a running total in a textbox underneath the 'table'. Is there a way using JavaScript that this can be done? I have my drop down boxes with values in them.

This is a snippet of my code:

function eraseText() {
    var out = document.querySelectorAll(".out");
    for (var i=0;i<out.length;i++) {
      out[i].value="";
    }
}

var sections = {

  p1 : {sname: "Dynamic Table   ", mscore: 20},
  p2 : {sname: "IntelliJ Usage  ", mscore: 10},
  p3 : {sname: "Calender Control", mscore: 30},
  p4 : {sname: "Active Form     ", mscore: 20},
  p5 : {sname: "Object Database ", mscore: 20}
};

document.write("<pre>");
document.write(Object.keys(sections).reduce(function(s, p, i) {
   var o = sections[p];
   return s + (i>0?'<br><br><br><br>':'') 
     + o.sname + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' 
     + o.mscore + '&nbsp;&nbsp;&nbsp;' 
     + '<textarea class="out" id="output" rows="4" cols="25"></textarea>' 
     + '&nbsp;&nbsp;&nbsp;' 
     + '<select>'
     + '<option value="1">1</option>'
     + '<option value="2">2</option>'
     + '<option value="3">3</option>'
     + '</select>' }, '')
);
document.write("</pre>");

Upvotes: 0

Views: 160

Answers (2)

jmcgriz
jmcgriz

Reputation: 3368

You'd want to bind to the onchange event of each select, and recalculate the sum each time.

var output = document.getElementById('output'),
  selects = document.querySelectorAll('select');

//helper method
function doToAll(elems, fn) {
  var len = elems.length;
  while (--len > -1) {
    fn(elems[len]);
  }
}

//sum values
function sumSelects() {
  var sum = 0;
  doToAll(selects, function(t) {
    sum += parseInt(t.value);
  });
  return sum;
}

//bind to onchange event
doToAll(selects, function(t) {
  t.addEventListener('change', function() {
    output.textContent = sumSelects();
  });
});

//run once on load
window.addEventListener('load', function() {
  output.textContent = sumSelects();
});
<select>
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
</select>
<select>
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
</select>
<select>
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
</select>
<p>The current total is
  <span id="output"></span>
</p>

Upvotes: 1

Brent L
Brent L

Reputation: 801

Something like this?

var selects = [].slice.call(document.querySelectorAll('select')); // [].slice.call turns NodeList into an array
var total = selects.reduce(function (previousValue, select) {
   previousValue += select.options[select.selectedIndex].value || 0;
}, 0);
// ... then query for textbox, set the value of it to 'total'

Upvotes: 4

Related Questions