Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My table can calculate the average, but I want to add an alert with this condition.

1. If the difference between input1 and input2 (that is input1 - input2) is greater than 0.3 (an alert should popup saying "NOT REPEATABLE."
But if the results are close to each other (that is, if input1 - input2 is less than or equal to 0.3), then no alert must be displayed.

NB: The table should keep on calculating the average, but I want to add that feature discribed above.
How do I add that alert in my code below?

What I have tried:

HTML
<!DOCTYPE html>

<html>
    <head>
        
        <title>calculate</title>
    </head>
    <script>     
        const reducer=(a,c)=>a+c;
        const average=(n)=>parseFloat( n.value ) / 2 || 0;
        
        const keyuphandler=(e)=>{
          if( e.target instanceof HTMLInputElement && e.target.type=='text' ){
        
            let table=e.target.closest('table');
            let tr=e.target.closest('tr');
            
            let group=tr.dataset.group;
            let elem=e.target.dataset.elem;

            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`);
            
            result.value = [...inputs]
              .map( average )
              .reduce( reducer, 0 )
          }
        };

        document.addEventListener('keyup',keyuphandler);

      </script>
      <style>
        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;
        }
       
        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;}

      </style>
       <body>

        <table>
          <tr>
            <th>%<br />Carbon</th>
            <th>Average<br />Carbon</th>
          </tr>
          
          <tr data-group=1>
            <td><input type='text' class='input' 
            data-elem='carbon' placeholder="input1"/></td>
            <td><input type='text' class='result' 
            data-elem='carbon' readonly placeholder="average" /></td>
          </tr>
          <tr data-group=1>
            <td><input type='text' class='input' 
            data-elem='carbon' placeholder="input2" /></td>
            <td colspan=2> </td>
          </tr>
        </body>
      </table>
</html>
Posted
Updated 10-Aug-23 6:27am
v3

1 solution

You need to modify your JavaScript to handle the Alert. I added a new condition inside your keyuphandler function to check if the current input elements belong to the carbon group and if the group is 1. If this condition is met, it calculates the difference between input1 and input2 and displays an alert if the difference is greater than 0.3 -
HTML
<!DOCTYPE html>
<html>
<head>
    <title>calculate</title>
</head>
<script>
    const reducer = (a, c) => a + c;
    const average = (n) => parseFloat(n.value) / 2 || 0;

    const keyuphandler = (e) => {
        if (e.target instanceof HTMLInputElement && e.target.type == 'text') {

            let table = e.target.closest('table');
            let tr = e.target.closest('tr');

            let group = tr.dataset.group;
            let elem = e.target.dataset.elem;

            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`);

            // Calculate the average
            result.value = [...inputs]
                .map(average)
                .reduce(reducer, 0);

            // Check if the difference between input1 and input2 
            // is greater than 0.3
            if (elem === 'carbon' && group === '1') {
                const input1 = parseFloat(inputs[0].value);
                const input2 = parseFloat(inputs[1].value);
                const difference = Math.abs(input1 - input2);
                if (difference > 0.3) {
                    alert("NOT REPEATABLE.");
                }
            }
        }
    };

    document.addEventListener('keyup', keyuphandler);
</script>
<style>
    /* ... (unchanged styling) ... */
</style>
<body>
    <table>
        <!-- ... (unchanged table structure) ... -->
    </table>
</body>
</html>

Your issue with using this inside the keyuphandler is that an alert will popup everytime a key is pressed until the full value has been entered. Not what you want. I have added the event to a button click, probably also not what you want, you need to change the code to do exactly what you require, this will point you in the right direction though:
JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>calculate</title>
</head>
<script>
    const reducer = (a, c) => a + c;
    const average = (n) => parseFloat(n.value) / 2 || 0;

    const calculateAndCheckDifference = () => {
        const table = document.querySelector('table');
        const input1 = parseFloat(table.querySelector
        ('tr[data-group="1"] input[data-elem="carbon"][data-input="1"]').value);
        const input2 = parseFloat(table.querySelector
        ('tr[data-group="1"] input[data-elem="carbon"][data-input="2"]').value);
        const result = table.querySelector('tr[data-group="1"] 
                       input[data-elem="carbon"].result');

        // Calculate the average
        result.value = average(table.querySelector('tr[data-group="1"] 
        input[data-elem="carbon"][data-input="1"]'));

        // Check if the difference between input1 and input2 
        // is greater than 0.3
        const difference = Math.abs(input1 - input2);
        if (difference > 0.3) {
            alert("NOT REPEATABLE.");
        }
    };
</script>
<style>
    /* ... (unchanged styling) ... */
</style>
<body>
    <table>
        <tr>
            <th>%<br />Carbon</th>
            <th>Average<br />Carbon</th>
        </tr>

        <tr data-group="1">
            <td><input type="text" class="input" 
            data-elem="carbon" data-input="1" placeholder="input1" /></td>
            <td><input type="text" class="result" 
            data-elem="carbon" readonly placeholder="average" /></td>
        </tr>
        <tr data-group="1">
            <td><input type="text" class="input" 
            data-elem="carbon" data-input="2" placeholder="input2" /></td>
            <td colspan="2"> </td>
        </tr>
    </table>
    <button onclick="calculateAndCheckDifference()">Calculate and Check</button>
</body>
</html>


You can see a working fiddle on both:

  1. On using keypress - Keyuphandler[^]
  2. On using a button element - Using a button to calculate[^]
 
Share this answer
 
v2
Comments
Ndambakuwa Mabarira 11-Aug-23 9:51am    
you are a star.you answered it all on using a button element.thanx a lot
Andre Oosthuizen 11-Aug-23 10:22am    
You are welcome, please mark the post as solved to close it, thank you.
Ndambakuwa Mabarira 13-Aug-23 16:58pm    
One more thing please.
i want to duplicate the table multiple times and i want the same code to run the same way its doin on this table.for example if i add more inputs and a button to calculate,it should respond the same way as on that first table.i tried it but i failed.am still learning javascript.
Andre Oosthuizen 14-Aug-23 3:37am    
a Totally new question which I saw you posted already. This post is solved.
Ndambakuwa Mabarira 14-Aug-23 17:25pm    
thanx i didnt know how it works cz am new on this platform.i accepted the solution for this question.
You can help me on that new question that i posted if you can.i am still new with javascript and the answer that i saw on my new post is not clear to me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900