To calculate the sum of input field rows that are filled in upon button click using predetermined values (HTML, CSS, JavaScript)

Greetings for exploring this content.

I have been creating a survey that involves rows of buttons which, when clicked, populate input fields with ratings ranging from 5 to -5.

The current code fills in one of two input fields located on opposite sides of the row.

This process essentially involves "populate, rinse, and repeat" for each row using the same block of code.

Now, I find myself dealing with multiple rows that need to be summed up to obtain a final total.

Some rows are now simplified to either 1 through 5 or -1 through -5.

I am seeking assistance for the predicament at hand as it is quite perplexing...

Any form of help would be greatly appreciated.

// JavaScript function included above
// CSS styles mentioned above
// HTML markup shown above

Answer №1

If you want to retrieve all elements containing the value of a specific row, target those elements with the class .count-plus or .count-minus.

Loop through each element and calculate their values by converting them from strings to integers using parseInt(StringVal).

Finally, display the total sum in a separate element. I've enhanced your code by incorporating functions to accumulate the sum and output it to a new element.

Here are some references for the methods used:
Array.prototype.reduce()
Destructuring Assignment


function changeValue(sender, value){
       var valueType1, valueType2, backgroundPlus, backgroundMinus, backgroundSelected, sibling, plusEls, minusEls;
       var row = sender.parentNode.parentNode;
       var parentDiv = row.closest('div');
       backgroundPlus = 'background-color:rgba(0,255,0,0.2);';
       backgroundMinus = 'background-color:rgba(255,0,0,0.2);';
       if (value > 0) {
           valueType1 = 'plus';
           valueType2 = 'minus';
           plusEls = row.querySelectorAll('.select-plus');
           minusEls = parentDiv.nextElementSibling.querySelectorAll('.select-minus');
           sibling = parentDiv.nextElementSibling;
           backgroundSelected = 'background-color:rgba(0,255,0);';
       } else {
           valueType1 = 'minus';
           valueType2 = 'plus';
           plusEls = parentDiv.previousElementSibling.querySelectorAll('.select-plus');
           minusEls = row.querySelectorAll('.select-minus');
           sibling = parentDiv.previousElementSibling;
           backgroundSelected = 'background-color:rgba(255,0,0); color:#fff;';
       }
       row.querySelector(".count-" + valueType1).value = 1*value;
       plusEls.forEach(function(el) {
           el.style.cssText = backgroundPlus;
       });
       minusEls.forEach(function(el) {
           el.style.cssText = backgroundMinus;
       });
       sender.style.cssText = backgroundSelected;
       sibling.querySelector(".count-" + valueType2).value = "";
   }
   
   // A helper Function to store the result in a new Element
  function getTotalCount(){
    const sum = sumCounts();
    const resultEl = document.querySelector('#sumField');
    resultEl.innerText = sum;
  }

   // "Independant" Function to sum the Values
   function sumCounts(){
    // We get all Field with the classes either .count-plus or .count-minus by using a simple 
    // CSS-Selector. It returns a NodeList storing all matched elements.
    let fields = document.querySelectorAll('.count-plus,.count-minus');

    // I then need to transform this NodeList into a usual Array by using the destructuring 
    // assignment, which takes all elements of an Iteratable-List and storing them into a new 
    // Array.
    // With .reduce i iterate through the entire Array and reduce it to a single Value. In this 
    // case i iterate through all Elements and sum their value and return the new Sum for the 
    // next iteration.
    let sum = [...fields].reduce((sum, field) => {
      sum += parseInt(field.value) || 0;
      return sum;
    }, 0);
    
    // Lastly i just return the sum.
    return sum;
   }
<style>
    body {
        display:block; width:100%; height:100%; min-height:1000px; margin:0 auto; padding:0; background-color:#fff; top:0; left:0;
        }
    .select-plus {
        display:block;
        float:left;
        height:40px; width:40px; margin:0 2px; border-radius:50%; background-color:rgba(0,255,0,0.2); color:#000; font-size:.85rem; font-weight:400;
    }
    .select-minus {
        height:40px; width:40px; margin:0 2px; border-radius:50%; background-color:rgba(255,0,0,0.2); color:#000; font-size:.85rem; font-weight:400;
    }
    .count-plus, .count-minus {
        height:40px; width:40px; margin:0 auto; text-align:center; font-size:1.1rem; font-weight:700; border:0; border-bottom:3px solid #000;
    }
    .count-plus {
        display:block;
        float:left;
        margin-right:10px;
        background:none;
    }
    .count-minus {
        display:block;
        float:right;
        margin-left:10px;
        background:none;
    }
    .bizModelRatingTableLabel {
        padding:0;
    }
    label {
        text-align:left;
        font-size:1rem;
    }
    table.bizModelRatingTable tbody tr td {
        margin:0;
        padding:0;
    }
</style>
<div style="display:block; float:left; width:50%;">
<table class="bizModelRatingTable" cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td><input type="text" class="count-plus" value=""></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 5)" value="5"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 4)" value="4"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 3)" value="3"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 2)" value="2"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 1)" value="1"></td>
  </tr>
</table>
</div>
<div style="display:block; float:left; width:50%;">
<table class="bizModelRatingTable" cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td><input class="select-minus" type="button" onclick="changeValue(this, -1)" value="-1">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -2)" value="-2">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -3)" value="-3">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -4)" value="-4">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -5)" value="-5">
    <td><input type="text" class="count-minus" value="">
  </tr>
</table>
</div>
<div style="display:block; float:left; width:50%;">
<table class="bizModelRatingTable" cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td><input type="text" class="count-plus" value=""></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 5)" value="5"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 4)" value="4"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 3)" value="3"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 2)" value="2"></td>
    <td><input class="select-plus" type="button" onclick="changeValue(this, 1)" value="1"></td>
  </tr>
</table>
</div>
<div style="display:block; float:left; width:50%;">
<table class="bizModelRatingTable" cellspacing="0" cellpadding="0" border="0">
  <tr>
    <td><input class="select-minus" type="button" onclick="changeValue(this, -1)" value="-1">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -2)" value="-2">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -3)" value="-3">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -4)" value="-4">
    <td><input class="select-minus" type="button" onclick="changeValue(this, -5)" value="-5">
    <td><input type="text" class="count-minus" value="">
  </tr>
</table>
<button onclick="getTotalCount()">Sum Counts</button>
<span id="sumField"></span>
</div>

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

What is the best way to handle various sections with changing structures within a complex form using react-hook-form?

I am working on a complex form that has sections A, B, and C, each of which can be in shape A1 or A2, B1 or B2, C1, or C2. Users are required to fill out settings based on whether the section is set to "advanced" or "basic". I want users to submit the enti ...

Looking to change the input field names by increasing or decreasing when clicking on a div using jQuery?

As a beginner in the world of jQuery, I am working on mastering some basic concepts. Currently, my goal is to create auto incrementing/decrementing input field names within a 'div' when clicking on an add/remove button. Below is the HTML code I a ...

Contrast between PHP and JavaScript output texts

Hey everyone, I'm dealing with a bit of an awkward situation here. I am trying to return a string variable from PHP to JavaScript and use it for a simple comparison in my code. However, the results are not turning out as expected. Initially, I send a ...

A guide on generating indices for icosahedronbuffergeometry using three.js

I am facing an issue and struggling to find a solution. I am looking for an alternative method to texture a sphere in three.js by using icosahedronbuffergeometry instead of spherebuffergeometry with additional code to generate indices for rendering using d ...

Looking to transition from Angular 1.5x to ReactJS, what is the most effective method for conducting A/B tests and exploring different views?

As I transition part of the UI code to ReactJS, I am considering A/B testing my app for instrumentation. I have looked into Intuit's Wasabi as a potential framework but found its setup process in production to be cumbersome. I am seeking an alternativ ...

Updating/Timer feature for a single feed out of two -- Combining data with $q.all()

I'm revisiting a question I previously asked here. The approach I took involved using the $q.all() method to resolve multiple http calls and then filtering and merging the data. Everything was working fine, but now I want to refresh one of the feeds ...

Simple way to retrieve the first and last date of the current month using Node.js

I need help with retrieving the first and last date of the current month using the code below:- let currentDate = new Date(); let month = currentDate.getMonth() + 1; console.log(month); let firstDate = new Date(currentDate.getFullYear(), currentDate.getMon ...

`The value of an element within an array changes automatically`

In my current setup, I have a traditional array where each element represents an HTML element. The issue arises when I manipulate these elements within the array; any changes made to the HTML element also reflect in the array automatically. However, I pref ...

Adding a custom class to a select2 dropdown: How can it be done?

I have customized select2 using CSS with its general classes and IDs. Currently, I am attempting to customize a specific class that will be assigned to select2 and then applied in the CSS. The problem lies not within the select itself, but within its dro ...

Tips for adjusting an @media css for a material-ui react component

After posting this inquiry about overriding a CSS property in a material-ui component, I received a helpful example. However, I encountered difficulty when attempting to set the height of the Toolbar component due to an overarching @media specification. My ...

The slides in Swiperjs are having trouble moving smoothly

I am experiencing some challenges with swiperjs where the slides are not snapping to the next slide and I am unable to fetch the active index from them. Below is a snippet of my code where I am using typescript, swiperjs version 6.84, and the Ionic frame ...

I'm having an issue with my progress bar in ReactJS - it seems to move when I scroll the window instead of

My code includes a progress bar that works fine - it shows a movable progress bar when the window is scrolled. However, I want the progress bar to move when scrolling inside my div, not on the entire window. I am currently using jQuery for this functionali ...

Printing dynamic data

When the print button is clicked, I need to print dynamically generated data from a table that has an ID. The table data (td and tr) is dynamically generated. I have successfully retrieved the table data and attempted to print everything using window.prin ...

What is the best way to adjust the row and column layout in bootstrap?

As I was creating a layout to showcase all of the bootstrap cards in a neat and organized manner, I noticed a peculiar issue that's been bothering me. Everything looks great when the columns are filled or when there's only one card present. Howev ...

Traversing a hierarchical JSON structure reminiscent of a tree object

I am working with a complex object structure, var cObj = { name: 'Object1', oNumbers: 3, leaf: [ { name: 'Inner Object 1', oNumbers: 4, leaf: [] }, { name: 'Inner Object 2', oN ...

Words fail to display

.sport { content: url("../img/sport.png"); background-color: rgba(0,0,0,1.0); top: 61px; height: 310px; width: 300px; position: absolute; margin: 0; left: 0; border-radius: 4px; overflow: hidden; } .sportsandactivis { background-colo ...

Tips for accessing touch events within the parent component's area in React Native

I implemented the code below in my React Native app to disable touch functionality on a specific child component. However, I encountered an issue where the touch event was not being detected within the area of the child component. How can I fix this prob ...

NuxtJs: Oops! It looks like NuxtError is not defined in this context

Exploring NuxtJs is new to me. I decided to experiment with how nuxt-link functions by purposely setting up a nuxt-link to a non-existent route in order to trigger the default 404 page. Here's the line of code I added to the pages/index.vue file: < ...

What is the method for extracting latitude and longitude values individually from JSON data?

Upon receiving the JSON response from the Google Maps API stored in a variable named 'obj', I noticed that alerting obj.name returns "Pancakes on the Rocks". To access the icon, I can use obj.icon. However, I am struggling to retrieve separate va ...

Moving pictures using css3 transitions

Trying to create a straightforward image slider. Below is the provided JavaScript code: $(document).ready(function() { $('#slide1_images').on('click', 'img', function(){ $("#slide1_images").css("transform","translateX ...