Tallying outcomes using JavaScript

I encountered a particular challenge: I have designed a table for user interaction, with results displayed at the end of each row. Just out of curiosity, I would like to count how many results are present in the table without performing any calculations. Is there a way to achieve this using Javascript? Thank you.

Below is the code for my table:

<table id="example" class="striped">
    <thead>
        <tr>
            <th>Objectives</th>
            <th> <center>Start Date </center></th>
            <th> <center>End Date </center></th>
            <th>Initial Evaluation</th>
            <th>  <center>Goal </center></th>
            <th>Interim Evaluation</th>
            <th>Final Evaluation</th>
            <th>Result (%)</th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <th>Objective 1</th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
        <tr>
            <th>Objective 2</th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
            <th></th>
        </tr>
    </tbody>
</table>

The two rows in the table above contain fields that calculate values based on user input. However, as not all users may complete both entries, I am interested in determining the total number of calculated results derived from the available data.

View image description here

Answer №1

Your JavaScript code will play a crucial role in resolving this issue. Here is my method:

Step 1: modify the id="AvIntercalar" to id="AvIntercalar1" and do the same for object2

function calculateResult(id){

    // Perform your calculations here

    var initialAverage = document.getElementById('avInicial'+id).value;
    var meta = document.getElementById('meta'+id).value;
    var intercalarAverage = document.getElementById('AvIntercalar'+id).value; 
    var averageFinal = document.getElementById('avFinal'+id).value;

    var result = Number(initialAverage) + Number(meta) + Number(averageFinal);
  
    // Set the calculated value
    document.getElementById("resultado"+id).value = result;

}
#

begin snippet

#

// Global array validObjects 
var validObjects = [];

function calculateResult(id) {

    //just do your maths here(I cannot understand your language)

    var initialAverage = document.getElementById('avInicial' + id).value;
    var meta = document.getElementById('meta' + id).value;
    var intercalarAverage = document.getElementById('AvIntercalar' + id).value;
    var averageFinal = document.getElementById('avFinal' + id).value;

    var result = Number(initialAverage) + Number(meta) + Number(averageFinal) + Number(intercalarAverage);

    // Set the value as required
    document.getElementById("resultado" + id).value = result;

    // this code will run when result is valid, otherwise no reaction
    if (result && validObjects.indexOf(id) == -1) {
        validObjects.push(id);
        document.getElementById('count').innerText = "Valid Results: " + validObjects.length;
    } else {
        validObjects.splice(validObjects.indexOf(id), 1);
        document.getElementById('count').innerText = "Valid Results: " + validObjects.length;
    }

}
<h2 id="count"></h2>
<table id="example" class="striped">
  <thead>
    <tr>
      <th>Objectives</th>
      <th>
        <center>Start Date</center>
      </th>
      <th>
        <center>End Date</center>
      </th>
      <th>Initial Evaluation</th>
      <th>
        <center>Goal</center>
      </th>
      <th>Interim Evaluation</th>
      <th>Final Evaluation</th>
      <th>Result (%)</th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <th>Objective 1</th>
      <th>
        <div class="input-field col s12">
          <input id="StartDate" type="date" class="datepicker" name="StartDate" />
          <label for="startdate"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="EndDate" type="date" class="datepicker" name="EndDate" />
          <label for="enddate"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="avInicial1" type="text" class="validate" autocomplete="off" name="InitialEvaluation" onchange="calculateResult(1)">
          <label for="initialvaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="goal1" type="text" class="validate" autocomplete="off" name="Goal" onchange="calculateResult(1)">
          <label for="goal"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="AvIntercalar1" type="text" class="validate" autocomplete="off" name="InterimEvaluation">
          <label for="interimevaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="avFinal1" type="text" class="validate" autocomplete="off" name="FinalEvaluation" onchange="calculateResult(1)">
          <label for="finalevaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input disabled id="resultado1" name="ResultUni" />
          <label for="resultuni" onchange="calculateFinalAverage()"></label>
        </div>
      </th>
    </tr>
    <tr>
      <th>Objective 2</th>
      <th>
        <div class="input-field col s12">
          <input id="StartDate" type="date" class="datepicker" name="StartDate" />
          <label for="startdate"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="EndDate" type="date" class="datepicker" name="EndDate" />
          <label for="enddate"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="avInicial2" type="text" class="validate" autocomplete="off" name="InitialEvaluation" onchange="calculateResult(2)">
          <label for="initialvaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="goal2" type="text" class="validate" autocomplete="off" name="Goal" onchange="calculateResult(2)">
          <label for="goal"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="AvIntercalar2" type="text" class="validate" autocomplete="off" name="InterimEvaluation">
          <label for="interimevaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input id="avFinal2" type="text" class="validate" autocomplete="off" name="FinalEvaluation" onchange="calculateResult(2)">
          <label for="finalevaluation"></label>
        </div>
      </th>
      <th>
        <div class="input-field col s12">
          <input disabled id="resultado2" name="ResultUni" />
          <label for="resultuni" onchange="calculateFinalAverage()"></label>
        </div>
      </th>
    </tr>
  </tbody>
</table>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Utilizing JavaScript, you can remove an element by clicking on the outer element within the

I need the functionality where, when a user clicks on an input type="checkbox", a corresponding textarea is displayed. Then, if the user clicks anywhere except for that specific textarea, it should be hidden. Can someone assist me with implementing this fe ...

Experience the power of dynamic site regeneration with GatsbyJS

Currently, I am working on a website built in GatsbyJS that deals with large datasets of dynamic content fetched using React fetch upon page load. The challenge here is to display semi-live data that updates every 5 minutes. I am curious about how I can m ...

The interplay between javascript and PL/SQL tasks in a dynamic scenario

I'm attempting to run multiple pl/sql blocks within a Dynamic Action, providing real-time feedback to the user through a modal dialog displaying the current status. Here is an example of what I am trying to achieve: Processing Step 1... /*Run pl/s ...

Upon initial login, React fails to retrieve notes

I developed a note-taking React app using the MERN stack with React Router DOM v6. When I initially visit the website, I am directed to the login page as intended. However, upon logging in, the page refreshes but does not redirect to the home page. This is ...

Best practices for resolving classlist.toggle issues with my dark mode button

The code seems to work only the first time, but after activating light mode again, the sun stops appearing. How can I ensure that the 'bi-sun' class is added back every other click or when dark mode is not activated? function theme() { do ...

Guide on retrieving information from Spark and showcasing it through Angular

Trying to navigate the world of Spark framework and AngularJS as a beginner, I set out to create a basic REST application. However, I hit a roadblock when it came to retrieving data from the server and displaying it using Angular. My initial task was simp ...

The function setState() is not performing as expected within the useEffect() hook

After retrieving data from my Mongo database, it's returned as an object within the useEffect hook function, specifically in the response. I then initialize a state called myorders with the intention of setting its value to the data fetched from the A ...

Revise the "Add to Cart" button (form) to make selecting a variant mandatory

At our store, we've noticed that customers often forget to select a size or version before clicking "Add to Cart" on product pages, leading to cart abandonment. We want to add code that prevents the button from working unless a variant has been chosen ...

Ensuring that the image perfectly fills the entire screen on an iPhone X using React Native

Looking for a solution to make my image fit the entire screen on the iPhone X simulator. I've tried adjusting the imageContainer width to "100%" and the container that encompasses everything, but haven't had any luck. Would appreciate any suggest ...

AngularJS is throwing an error claiming that the controller is not defined and is not a function

Struggling to create a basic angular application, every time I attempt it, I encounter this issue and can never find a solution. The content of App.js is as follows: angular.module('Euclid', ['ui.bootstrap', 'ngRo ...

Selenium - Tips for entering text in a dynamically generated text field using Javascript!

I'm fairly new to the world of web scraping and browser automation, so any guidance would be greatly appreciated! Using Python's Selenium package, my objective is: Navigate to Login using the provided username & password Complete my order thr ...

Unable to establish a breakpoint in a source-mapped file (illustrated using jQuery)

Having trouble setting a breakpoint on a minified JavaScript source file that is mapped to real sources using a source map file. An example of this problem can be seen on the website jquery.com. On this particular site, the imported script is jquery.min. ...

What is the best method for determining values within JSON data?

In my possession is a JSON file containing user data that looks like this: [ { "id": 0, "username": "Antony", "users": [ { "id& ...

Failed to fetch user id from server using Ajax request

I am facing an issue with my form that includes a text input field and a button. After submitting the form, I extract the value from the user field and send an ajax request to ajax.php to retrieve the userID from the server. The server does return a value, ...

Looking to trigger the closing of a q-popup-proxy by clicking a button from a separate component

I am currently working with a q-popup-proxy component in my project. <q-btn label="Add Fault" class="addFaultButton" dense @click="openPopUp()"> <q-popup-proxy position="center" v-if="openFaults" ...

The AngularJS HTTP interceptor is a crucial component for handling

Is there a way to use an interceptor in AngularJS to log "finished AJAX request" when any request is completed? I've been exploring interceptors and currently have the following setup, but it triggers at the beginning of the request rather than the e ...

jQuery Mishap - Creating an Unspecified Issue

At the moment, my website displays a list of registered users in one column and their email addresses with checkboxes next to them in another column. Users can check the boxes and then click a submit button to generate a list of the selected emails separat ...

Exploring Database with NodeJS, Express, and HTML

My goal is to create a basic web application using node.js where users can input data into a search bar and have that input sent to the server for database query. While I've successfully set up and connected my database, here's a glimpse of my co ...

The functionality of React-router-dom protected routes seems to be malfunctioning

Understanding Protected Routes in React.js: While looking at the implementation of protected routes, you may notice that 'false' is being directly used in the if statement. However, even with this condition, the page is still accessible. Why doe ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...