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

The slideshow feature on W3 Schools does not start automatically when the page loads

After following the W3Schools tutorial to create a slideshow, I found that the animations are working correctly. However, only three dots appear on the screen and I have to manually click on one of them to view the pictures. var slideIndex = 0; sh ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

Gathering feedback from a webpage using JavaScript and jQuery

I have been experimenting with different tools such as Selenium and BeautifulSoup in an attempt to scrape the contents of the following website/pages: . Specifically, I am looking to extract the reviews/sections which are dynamically loaded by JS, jQuery ...

What are the steps to use the vue-text-highlight feature?

I am attempting to implement an example from the basic usage section of https://github.com/AlbertLucianto/vue-text-highlight. However, upon opening index.html in Firefox, I am only greeted with a blank page. You can find the code I am using at https://git ...

The media query was running smoothly until it unexpectedly stopped functioning

I've encountered an issue where something that used to work perfectly fine suddenly stopped working :( @media only screen and (max-width: 768px) { form, button, input { width: 80vw !important; } } <meta name="viewport" content="width=de ...

Teaching jQuery selectors to detect recently-added HTML elements

Unable to find a solution in the jQuery documentation, I am seeking help here for my specific issue. Embracing the DRY principle, I aim to utilize JavaScript to include a character countdown helper to any textarea element with maxlength and aria-described ...

Is it possible to display a value conditionally based on a condition from a Json object?

I'm looking to add a new feature that displays all the movies featuring Sean Connery in a button, but I'm stuck on how to implement it. Prettier 2.7.1 --parser babel Input: import React, { useState } from "react"; import styled ...

A fresh PHP page escapes from the confines of an iframe and expands to occupy the entire

When calling a new url from inside an iframe, the goal is for the new url to break free from the confines of the iframe and appear full screen. The challenge lies in not having control over the call to the new php file, as it is initiated by a credit card ...

Issues with the functionality of customisable list items in a list

I am attempting to customize the appearance of specific list items within a ul element. One li element should be displayed in red font, while another li element should have a hyperlink styled with a different color and an underline rollover effect. The thi ...

Continuously receiving the "Add to home screen" prompt despite already installing the PWA app

Is there a method to determine if the Progressive Web App has already been installed? It is possible to cancel the prompt event in the 'beforeinstallprompt' event. window.addEventListener('beforeinstallprompt', (event) => { // co ...

The use of Angular's ngClass directive does not work within the link function

I have a straightforward directive that renders an element, and this is the template: <div class="nav-item"></div> The .nav-item class looks like this: .nav-item { height: 50; } Here's the directive in action: angular.module('m ...

Attempting to utilize a for loop in JavaScript to condense code, however encountering a "not defined" error

I'm relatively new to working with javascript and currently attempting to enhance the following code snippet (which has been tested and is functioning correctly): // snail 1 // var s1 = document.createElement("div"); s1.id = snail1.id; s1.className = ...

Tips for identifying MIME type errors in an Angular 9 application and receiving alerts

While working on my Angular app, I encountered the MIME type error Failed to load module script: The server responded with a non-javascript mime type of text/html. Fortunately, I was able to resolve it. Now, I'm stuck trying to figure out how to rece ...

Execute JavaScript using "matches" without the need for the page to refresh

I have been developing a school project which involves creating a Chrome extension to streamline the Checkout process on a website. In my manifest.json file, I specified that a content.js file should run when it matches a specific URL. "content_script ...

Arranging elements in columns using Bootstrap

I am facing an issue with my columns in bootstrap, as they are currently appearing vertically, one above the other. I need them to be displayed side by side Here is the code I am using: <div class="col-xl-4 col-lg-6 col-md-6 col-sm-12 col-12 layo ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

Spinning text within a circular rotation in CSS

Looking for guidance on how to center the "hallo" text inside a circle? Currently experiencing issues with the circle display in IE8 and Firefox. Any suggestions on how to fix this would be greatly appreciated. And here is the link to my code snippet: CSS ...

The "scrollTop" function seems to be malfunctioning in Firefox but works perfectly fine in Chrome. Is there a way to fix this issue?

Issue with scrollTop in Firefox jQuery(window).scroll(function(){ var NextScroll = jQuery(this).scrollTop(); if (NextScroll >= 800){ jQuery('#logomacchia').addClass("maccancello"); } else { jQuery('#logomacch ...

Running Javascript based on the output of PHP code

I have been working on my code with test.php that should trigger some Javascript when my PHP code, conditional.php, detects input and submits it. However, instead of executing the expected "Do Something in Javascript," it outputs "Not empty" instead. I fin ...

Place an image at the center with a height set to 100% within a div that has a fixed height and

Apologies for asking about this topic again, but I have been unable to find a solution where the image fills 100% of the height. If you'd like to see the issue in action, here's a link to the jsfiddle: http://jsfiddle.net/BBQvd/3/ I'm just ...