menna menna - 1 year ago 65
HTML Question

Javascript how to allow array to take more than one digit?

I've been trying lately to build up a mean calculator using html and javascript. i want to take all the inputs from the one text box add them to an array and get the average result. what i did in the following code takes only one digit because of str[i-1] is there any other alternative way of doing it? Thanks!
Output photo

function calculate()

var str= document.getElementById("meanvalue").value;
for(var i=0; i<str.length; i++)
if(str[i] == ".")


Answer Source

Here is a small example:

document.getElementById('input').onkeyup = function() {
  this.value = this.value.replace(/[^0-9\.]/gi, '');// restrict non digit
  var sum = 0;
  var array = this.value.split(/\./);
  array.forEach(function(str) {
    sum += (parseInt(str, 10) || 0); //avoid NaN
  document.getElementById('output').value = (sum / array.length || 0);// avoid NaN
<input type="text" id="input" />
<input type="text" id="output" readonly='' />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download