skip to Main Content
<!DOCTYPE html>

<html>
    <head>
        
        <title>calculate average of two students</title>
        <script>
            
            function calc()
            {
                var n1 = parseFloat(document.getElementsByName('n1').value);
                var n2 = parseFloat(document.getElementsByName('n2').value);
                var n3 = parseFloat(document.getElementsByName('n3').value);
                var n4 = parseFloat(document.getElementsByName('n4').value);
                var n5 = parseFloat(document.getElementsByName('n5').value);
                var n6 = parseFloat(document.getElementsByName('n6').value);
                var n7 = parseFloat(document.getElementsByName('n7').value);
                var n8 = parseFloat(document.getElementsByName('n8').value);
                
                var oper = document.getElementById('operators').value;
                
            
                {
                    document.getElementById('result').value = n1/2 + n2/2;
                }
            }
        </script> 
        <style>
            table{
                width: 50px;
                border: 1px solid black;
                border-collapse: collapse;
            }
            td{
                border: 1px solid black;
                padding: 0px;
                font-size: 10px;
            }
            th{
                border: 1px solid black;
                padding: 0px;
            }
           
            form{
              width: 4px;
            }
            div{
              display: grid; 
            }
            label {
              display: block;
              width: 4px;
              font-size: 14px;
            }
            input [type="date"] {
              width: 4px;
            }
        </style>
    </head>
    <body>
        <table>
            <tr>
             
              <th rowspan="1" colspan="1">%<br>Sulphur</th>
              <th rowspan="1" colspan="1">%<br>Carbon</th>
              <th rowspan="1" colspan="1">Average<br>Sulphur</th>
              <th rowspan="1" colspan="1">Average<br>Carbon</th>
              
            </tr>
            <tr>
              <td><input type="text" name="n1" size="3" onkeyup="calc();">1</td>
              <td><input type="text" name="n3" size="3" onkeyup="calc();">3</td>
              <td>
                
            <input type="text" id="result" size="3.5" rowspan="2" colspan="1" readonly>5</td>
            <td><input type="text" id="result" size="3.5" rowspan="2" colspan="1" readonly>6</td>
              <td rowspan="2" colspan="1"></td>
            </td>
            </tr>
            <tr>
              
              <td><input type="text" id="n2" size="3" onkeyup="calc();">2</td>
              <td><input type="text" id="n4" size="3" onkeyup="calc();">4</td>
            </tr>
            
            <tr>
             
                <td><input type="text" name="n5" size="3" onkeyup="calc();">7</td>
                <td><input type="text" name="n7" size="3" onkeyup="calc();">9</td>
                <td><input type="text" id="result" size="3.5" rowspan="2" colspan="1" readonly>11</td>
              <td><input type="text" id="result" size="3.5" rowspan="2" colspan="1" readonly>12</td>
               
              </td>
              </tr>
              <tr>
                
                <td><input type="text" id="n6" size="3" onkeyup="calc();">8</td>
                <td><input type="text" id="n8" size="3" onkeyup="calc();">10</td>
              </tr>
    
        </table>
    </body>
</html>           

please refer to my table on my html table below to understand the question.
I created a table and for clarity`s sake i have numbered all my text boxes.i am trying to calculate the average of text input1 (% sulphur) and text input 2 (% sulphur) to get average result in a readonly text input5(average sulphur).this is for sulphur.

i am also trying to calculate the average of text input3(%carbon) and text input 4(%carbon) to get verage result in a readonly text input 6(average carbon).this is for carboon.

furthermore i want javascript to repeatedly do this to my next text inputs on the table which are input7 and input8 to get average in readonly input11.
the formular should also do the same to add input 9 and 10 to get average in readonly input12

2

Answers


  1. After looking at your code, I think I got what you tried to do.

    Is is something like this? I can explain more of what I’m doing if you are interested.

    const form1 = document.getElementById('form1');
    form1.addEventListener('keyup', calc);
    
    function calc() {
      const data = {
        sulphur1: [],
        sulphur2: [],
        carbon1: [],
        carbon2: [],
      };
    
      for (const [name, text] of new FormData(form1)) {
        if (name in data) data[name].push(parseFloat(text));
      }
    
      const elemAvgSulphur = Array.from(form1.querySelectorAll('[name=avgSulphur]'));
      const elemAvgCarbon = Array.from(form1.querySelectorAll('[name=avgCarbon]'));
    
      for (let idx = 0; idx < data.sulphur1.length; idx += 1) {
        let //
          sulphur1 = data.sulphur1[idx],
          sulphur2 = data.sulphur2[idx],
          carbon1 = data.carbon1[idx],
          carbon2 = data.carbon2[idx],
          avgSulphur = (sulphur1 + sulphur2) / 2,
          avgCarbon = (carbon1 + carbon2) / 2;
    
        elemAvgSulphur[idx].value = isNaN(avgSulphur) ? '' : avgSulphur.toFixed(1);
        elemAvgCarbon[idx].value = isNaN(avgCarbon) ? '' : avgCarbon.toFixed(1);
      }
    }
    table {
      border: 1px solid black;
      border-collapse: collapse;
    }
    
    td {
      border: 1px solid black;
      padding: 0px;
      font-size: 10px;
    }
    
    th {
      border: 1px solid black;
      padding: 0px;
    }
    
    input {
      width: 5ch;
      text-align: right;
    }
    <form id="form1">
      <table>
        <tr>
          <th>%<br />Sulphur</th>
          <th>%<br />Carbon</th>
          <th>Average<br />Sulphur</th>
          <th>Average<br />Carbon</th>
        </tr>
    
        <tr>
          <td><input type="text" name="sulphur1" /></td>
          <td><input type="text" name="carbon1" /></td>
    
          <td rowspan="2"><input type="text" name="avgSulphur" readonly /></td>
          <td rowspan="2"><input type="text" name="avgCarbon" readonly /></td>
        </tr>
    
        <tr>
          <td><input type="text" name="sulphur2" /></td>
          <td><input type="text" name="carbon2" /></td>
        </tr>
    
        <tr>
          <td><input type="text" name="sulphur1" /></td>
          <td><input type="text" name="carbon1" /></td>
          <td rowspan="2"><input type="text" name="avgSulphur" readonly /></td>
          <td rowspan="2"><input type="text" name="avgCarbon" readonly /></td>
        </tr>
    
        <tr>
          <td><input type="text" name="sulphur2" /></td>
          <td><input type="text" name="carbon2" /></td>
        </tr>
      </table>
    </form>
    Login or Signup to reply.
  2. If you were to adopt dataset attributes it would be possible to relate input and output elements in such a way that calculations could be done with any number of inputs. The notes within the javascript below should explain what is happening

    /*
      utility callbacks used within the calculation of the
      average numbers.
      
      reducer is used within the Array.reduce() method.
      average is used within the Array.map() method.
    */
    const reducer=(a,c)=>a+c;
    const average=(n)=>parseFloat( n.value ) / 2 || 0;
    
    
    /*
      A delegated event listener bound to the document (or suitable parent)
      listens for and processed keyup events if they originate from a 
      text input. This criteria could(should) be more focused in practice.
    */
    const keyuphandler=(e)=>{
      if( e.target instanceof HTMLInputElement && e.target.type=='text' ){
        /*
          Use the EVENT to identify HTML elements of interest.
        */
        let table=e.target.closest('table');
        let tr=e.target.closest('tr');
        
        let group=tr.dataset.group;
        let elem=e.target.dataset.elem;
        /*
          Using the above variables it becomes easy to identify other
          elements within the HTML now that we know the dataset attributes
          - note the HTML has multiple data-name type attributes that
          are used to relate the inputs according to chemical type
          and table row.
          
          inputs is a nodelist, not an array so must be converted to an array 
          so that we can use array methods "map" and "reduce"
          This is done using the "splat" or spread operator ...
          
        */
        let result=table.querySelector(`tr[data-group="${group}"] input[data-elem="${elem}"].result`);
        let inputs=table.querySelectorAll(`tr[data-group="${group}"] input[data-elem="${elem}"].input`);
        /*
          use array methods to perform calculations on the input
          values and assign the result to the correctly identified
          input.result element.
        */
        result.value = [...inputs]
          .map( average )
          .reduce( reducer, 0 )
      }
    };
    
    
    
    document.addEventListener('keyup',keyuphandler);
    table {
      width: 50px;
      box-sizing:border-box;
      border: 1px solid black;
      border-collapse: collapse;
      font-family:monospace
    }
    td {
      border: 1px solid black;
      padding: 0px;
      font-size: 10px;
    }
    th {
      border: 1px solid black;
      padding: 0px;
    }
    form {
      width: 4px;
    }
    div {
      display: grid;
    }
    label {
      display: block;
      width: 4px;
      font-size: 14px;
    }
    input [type="date"] {
      width: 4px;
    }
    
    
    
    
    
    
    
    
    /*
      following only to prettify
      example ;-)
    */
    table {
      box-sizing:border-box;
      font-family:monospace
    }
    td,th{padding:0.25rem;}
    
    [data-elem='carbon']{background:rgba(0,0,100,0.1)}
    [data-elem='sulphur']{background:rgba(0,100,0,0.1)}
    [readonly]{background:rgba(255,0,0,0.1)}
    
    .input{width:3rem}
    .result{width:3.5rem}
    input{border:1px solid grey;padding:0.2rem;}
    <!--
      Note: the names of input elements were (are) playing no part 
      in any calculations so were removed from the following.
    -->
    
    <table>
      <tr>
        <th>%<br />Sulphur</th>
        <th>%<br />Carbon</th>
        <th>Average<br />Sulphur</th>
        <th>Average<br />Carbon</th>
      </tr>
      
      <tr data-group=1>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td><input type='text' class='result' data-elem='sulphur' readonly /></td>
        <td><input type='text' class='result' data-elem='carbon' readonly /></td>
      </tr>
      <tr data-group=1>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td colspan=2>&nbsp;</td>
      </tr>
      
      <tr data-group=2>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td><input type='text' class='result' data-elem='sulphur' readonly /></td>
        <td><input type='text' class='result' data-elem='carbon' readonly /></td>
      </tr>
      <tr data-group=2>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td colspan=2>&nbsp;</td>
      </tr>
      
      <!-- 
        this can easily be extended by simply changing the data-group value
        of any addition table-row pairs added.
        eg:
        
      <tr data-group=3>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td><input type='text' class='result' data-elem='sulphur' readonly /></td>
        <td><input type='text' class='result' data-elem='carbon' readonly /></td>
      </tr>
      <tr data-group=3>
        <td><input type='text' class='input' data-elem='sulphur' /></td>
        <td><input type='text' class='input' data-elem='carbon' /></td>
        <td colspan=2>&nbsp;</td>
      </tr>
      -->
    </table>

    I appreciate that you are a beginner with Javascript so much of what you see here might well be very daunting and confusing. That said as your knowledge increases you will hopefully find value in some of the techniques shown here – but if you have questions you can ask away!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search