I am very new to JavaScript. In our class we were assigned a project to create a Web page with 5 text boxes, each with a value attribute of zero. When the user changes the values, it is supposed to call a caclAvg() function. How do I pass 5 values to the calcAvg() function? It specifically states in our book to create an onChange event handler for each textbox. Wouldn't it be easier to somehow create a variable onChange, then after all 5 textboxes have changed, pass the 5 variables along to the function? I know the following code is a mess, I've tried so many ways now. I'm sure this is an easy, routine procedure for most of you. Thanks for any help or suggestions you may have.

function calcAvg(value1) {
	var functionValue = value1;
}
	
<form action="" method="post" name"values">
    <input type="text" name="value1" value="0" onchange="calcAvg(this.value)" />
    <input type="text" name="value2" value="0" onchange="calcAvg(this.value);" />
    <input type="text" value="0" />
    <input type="text" value="0" />
    <input type="text" value="0" />
</form>

Dani AI

Generated

Simpler and more robust: have calcAvg read the five inputs from the DOM instead of trying to pass five separate values on every change. Passing all five inline (as showed) quickly becomes hard to maintain. Attaching a single handler to each input (as suggested) is the right idea — prefer modern addEventListener with DOMContentLoaded rather than custom load shims.

A minimal working pattern (different from the examples already posted):

<!-- mark the five inputs with a class and provide an output field -->
<form name="values">
  <input class="avg" type="text" value="0">
  <input class="avg" type="text" value="0">
  <input class="avg" type="text" value="0">
  <input class="avg" type="text" value="0">
  <input class="avg" type="text" value="0">
  <input id="average" type="text" readonly>
</form>

<script>
document.addEventListener('DOMContentLoaded', function () {
  var fields = document.querySelectorAll('input.avg');
  fields.forEach(function(f){ f.addEventListener('change', calcAvg); });
  function calcAvg() {
    var sum = 0, count = 0;
    fields.forEach(function(f){
      var n = parseFloat(f.value);
      if (!isNaN(n)) { sum += n; count++; }
    });
    document.getElementById('average').value = count ? (sum/count).toFixed(2) : '';
  }
  calcAvg(); // set initial average
});
</script>

Practical notes and gotchas: fix any HTML typos (for example the form attribute must be name="values"). Use parseFloat (or Number) and guard against NaN. type="number" with step="any" helps validation and mobile keyboards. Use the input event instead of change if live updates while typing are required. If the assignment truly requires “only after all five boxes have been changed at least once,” keep a small flags array or use dataset on each field to mark it edited and then compute once all five flags are set.

Reference: MDN has compact guidance on using addEventListener and modern DOM events — see the addEventListener docs for details (https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener).

Recommended Answers

All 5 Replies

Member Avatar for Member #733618

This works, but is a little extrange for you maybe...

<body>
    <script type="text/javascript">
    function calcAvg(value1, value2, value3, value4, value5) {
        var functionValue1 = value1;
        var functionValue2 = value2;
        var functionValue3 = value3;
        var functionValue4 = value4;
        var functionValue5 = value5;
        document.values.value11.value = functionValue1;
        document.values.value22.value = functionValue2;
        document.values.value33.value = functionValue3;
        document.values.value44.value = functionValue4;
        document.values.value55.value = functionValue5;
    }
    </script>
    <form action="" method="post" name="values">
    <input type="text" name="value1" value="0" onChange="calcAvg(this.value, document.values.value2.value, document.values.value3.value, document.values.value4.value, document.values.value5.value)"/>
    <input type="text" name="value2" value="0" onChange="calcAvg(document.values.value1.value;, this.value, document.values.value3.value;, document.values.value4.value, document.values.value5.value)"/>
    <input type="text" name="value3" value="0" onChange="calcAvg(document.values.value1.value, document.values.value2.value, this.value, document.values.value4.value, document.values.value5.value)"/>
    <input type="text" name="value4" value="0" onChange="calcAvg(document.values.value1.value, document.values.value2.value, document.values.value3.value, this.value, document.values.value5.value)"/>
    <input type="text" name="value5" value="0" onChange="calcAvg(document.values.value1.value, document.values.value2.value, document.values.value3.value, document.values.value4.value, this.value)"/>
    <br>
    <input type="text" name="value11" value=""/>
    <input type="text" name="value22" value=""/>
    <input type="text" name="value33" value=""/>
    <input type="text" name="value44" value=""/>
    <input type="text" name="value55" value=""/>
    </form>
</body>

When you modify some textbox and then press other you will see that the other text will have the same value than the other, but only works in the first textbox column, dont write in the second...

you could also try this, but it maybe overdoing it.

//just like the document.onload event
addLoadListener(test_function);

//makes sure that addLoadListener works across different browsers like IE or Firefox
// you don't really need it but it's good to know. 
function addLoadListener(fn){
    if(typeof window.addEventListener !='undefined')    window.addEventListener('load',fn,false);
    else if(typeof document.addEventListener !='undefined')    document.addEventListener('load',fn,false);
    else if(typeof window.attachEvent !='undefined')    window.attachEvent('onload',fn);
    else{
        var oldfn=window.onload
        if(typeof window.onload !='function')    window.onload=fn;
        else    window.onload=function(){oldfn();fn();}
    }
}

//this function runs as the document loads
function test_function(){
    
    //get all the INPUT elements on the page
    var input_fields = document.getElementsByTagName("input");
    //iterate through each element
    for(var i=0; i<input_fields.length; i++){
       //assign the onchange event to each input field then calles the calcAvg function
        input_fields[i].onchange=function() { calcAvg(this.value); };
    }
    
    
}

function calcAvg(value1) {
    var functionValue = value1;
        alert(functionValue);//just to test
}

//removed the onchange events

<form action="" method="post" name"values">
    <input type="text" name="value1" value="0" />
    <input type="text" name="value2" value="0" />
    <input type="text" value="0" />
    <input type="text" value="0" />
    <input type="text" value="0" />
</form>

this will allow you to eliminate adding ...onchange="calcAvg(this.value)" /> on each HTML element

Thank you both for your help! I will try these and see what I can come up with. qazplm, yes, I think that is way beyond my knowledge! Thanks to both of you for taking the time to help.

Thank you both for your help! I will try these and see what I can come up with. qazplm, yes, I think that is way beyond my knowledge! Thanks to both of you for taking the time to help.

No problem, it may be complicated at first but once you get used to the 'document object model' everything will be a 10 times more easier. Also, if you're used to CSS, try using the Jquery library, it's much more easier to use and it's free.

Member Avatar for Member #733618

;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.