Lee Attewell
Lee Attewell

Reputation: 13

Update textbox values in Javascript every second

I'm trying to translate a pay and savings calculator I made in excel to a web page I can host on my website and access anywhere.

What I want is to have the values automatically update without the need of pressing a load of buttons.

I've done a bit of research and put together this code, but its not working...

window.setInterval(function () {
  var week1 = document.getElementsByName("week1").value;
  var week2 = document.getElementsByName("week2").value;
  var week3 = document.getElementsByName("week3").value;
  var week4 = document.getElementsByName("week4").value;
  var week5 = document.getElementsByName("week5").value;

  var weekTotal = week1 + week2 + week3 + week4 + week5;

  document.getElementById("totalHours").innerHTML = weekTotal;
}, 1000);

Any ideas?

Upvotes: 1

Views: 2708

Answers (3)

RobG
RobG

Reputation: 147453

As an alternative to the answer you've selected, consider making use of the collections available and use property access rather than function calls. e.g.

<script>

// Test that v is an integer
function isInt(v) {
  return /^\d+$/.test(v + '');
}

// Update the total if entered value is an integer
function updateTotal(e) {
  var e = e || window.event;
  var el = e.target || e.srcElement;
  var value = el.value;

  // If value is an integer, use it
  if (isInt(value)) {
    el.form.total.value = +el.form.total.value + +value;

  // Otherwise, do nothing (or show an error message asking
  // the user to input a valid value)
  } else {
    e.preventDefault();
  }
  return false;
}

// Add listeners to elements that need them
window.onload = function() {
  var form = document.forms['f0'];
  var els = form.elements;
  var re = /^week/;
  var total = 0;

  for (var i=0, iLen=els.length; i<iLen; i++) {
    if (re.test(els[i].name)) {
      els[i].onchange = updateTotal;
    }
  }
}
</script>

<form id="f0" action="">
  week1<input name="week1" value="0"><br>
  week2<input name="week2" value="0"><br>
  week3<input name="week3" value="0"><br>
  week4<input name="week4" value="0"><br>
  week5<input name="week5" value="0"><br>
  total<input name="total" value="0" readonly>
  <input type="reset"><input type="submit">
</form>

The isInt function is a bit simple, it should trim leading and trailing spaces etc. but is sufficient to show that you must test the input before using it in an operation. This is also a great example of where inline listeners are probably a better solution.

Upvotes: 0

Alnitak
Alnitak

Reputation: 339947

  1. use element IDs, not names - then you can use document.getElementById()

  2. cache those element variables so you don't have to call document.getElementById() every time

  3. convert .value into a number with parseInt(s, 10) - although you haven't said how it fails this will be causing you a problem because .value is normally a string and using + on strings does concatenation, not addition.

  4. don't do it in a timer loop - it'll prevent updates from happening in real time. Instead, use an onchange (and/or oninput) event handler which will be called immediately whenever any value is updated. With onchange the sum would be calculated each time the user moves from one input to another, with oninput it'll recalculate on each key press (or copy/paste, etc).

See http://jsfiddle.net/alnitak/7Gzs6/

var form = document.getElementById('myform');
var inputs = form.getElementsByTagName('input');
var totalView = document.getElementById('total');

function add(ev) {
    var total = 0;
    for (var i = 0, n = inputs.length; i < n; ++i) {
        var v = parseInt(inputs[i].value, 10);
        if (!isNaN(v)) {
            total += v;
        }
    }
    totalView.innerHTML = total;
}

form.addEventListener('change', add, false);​

Upvotes: 2

lostsource
lostsource

Reputation: 21830

document.getElementsByName returns an array

So you probably want to retrieve the first element [0] with name 'week1' and so on.

var week1 = document.getElementsByName("week1")[0].value;

Upvotes: 0

Related Questions