Is there a more efficient method to execute this function on two distinct elements?

Dealing with a summing function for input field numbers to a single digit, I face the challenge of applying it to two separate fields upon clicking an HTML button. Rather than duplicating the function, is there a more efficient approach to achieve this?

function getSum1() {
const input = document.getElementById('dateInput1').value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
    const num = parseInt(input.charAt(i));
    if (!isNaN(num)) {
        sum += num;
         }
    }
  const total = (sum - 1) % 9 + 1;
    document.getElementById("result1").textContent = "Your number is: " + total;
}
function getSum2() {
const input = document.getElementById('dateInput2').value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
    const num = parseInt(input.charAt(i));
    if (!isNaN(num)) {
        sum += num;
         }
    }
  const total = (sum - 1) % 9 + 1;
    document.getElementById("result2").textContent = "Your number is: " + total;
}

<div class="container">
        <div class="cell-1"><input type="text" id="dateInput1"></div>
        <div class="cell-2"><img src="file:///Users/Nineborn/Downloads/My%20Post.png" alt=""></div>
        <div class="cell-3"><input type="text" id="dateInput2"></div>
        <div class="cell-4" id="result1"></div>
        <div class="cell-5"><button onclick="getSum1(); getSum2()">Calculate</button></div>
        <div class="cell-6" id="result2"></div>
        <div class="cell-7"></div>
        <div class="cell-8"></div>
        <div class="cell-9"></div>


    </div>

Answer №1

If you store the IDs of both the input and output elements in arrays, you can then iterate over the input array to execute the main operation for each item in the array.

function calculateTotal() {
  // Store the IDs of input and output elements in arrays
  let inputs = ['dateInput1', 'dateInput2'];
  let outputs = ['result1', 'result2'];
  
  // Loop through each item in the inputs array
  // This loop will run as many times as there are input elements
  inputs.forEach(function(input, index){

    // Instead of hard-coding element IDs, access them dynamically
    const inputValue = document.getElementById(input).value;
    var sum = 0;
    for (var i = 0; i < inputValue.length; i++) {
      const num = parseInt(inputValue.charAt(i));
      if (!isNaN(num)) {
        sum += num;
      }
    }
    const total = (sum - 1) % 9 + 1;
    // Update the correct output element based on the current index
    document.getElementById(outputs[index]).textContent = "Your number is: " + total;
  
  });
}
<div class="container">
        <div class="cell-1"><input type="text" id="dateInput1"></div>
        <div class="cell-2"><img src="file:///Users/Nineborn/Downloads/My%20Post.png" alt=""></div>
        <div class="cell-3"><input type="text" id="dateInput2"></div>
        <div class="cell-4" id="result1"></div>
        <div class="cell-5"><button onclick="calculateTotal();">Calculate</button></div>
        <div class="cell-6" id="result2"></div>
        <div class="cell-7"></div>
        <div class="cell-8"></div>
        <div class="cell-9"></div>
</div>

Answer №2

By working with the digits of an integer, you can apply the same approach to achieve consistency.

function calculateSum(value) {
  var sum = 0;
  while (value > 0) {
    sum += value % 10;
    value /= 10;
  }
}

Afterward, all that's left to do is

var inputNumber = document.getElementById('userInput').value;
inputNumber = calculateSum(parseInt(inputNumber));
document.getElementById("outputResult").textContent = "The total sum is: " + inputNumber;

Answer №3

For your specific ID/Class, you will reference it through the variable n:

function calculateTotal(n) {
const input = document.getElementById('userInput' + n).value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
    const num = parseInt(input.charAt(i));
    if (!isNaN(num)) {
        sum += num;
         }
    }
  const total = (sum - 1) % 9 + 1;
    document.getElementById("result" + n).textContent = "The calculated number is: " + total;
}

If you have different class names (n1 for input id, and n2 for result id), you can use this alternative function:

function calculateTotalDifferentIDs(n1, n2) {
const input = document.getElementById(n1).value;
var sum = 0;
for (var i = 0; i < input.length; i++) {
    const num = parseInt(input.charAt(i));
    if (!isNaN(num)) {
       sum += num;
        }
   }
  const total = (sum - 1) % 9 + 1;
    document.getElementById(n2).textContent = "The calculated number is: " + total;
}

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

Encountering issues with MVC Razor's Cascading Dropdown Validation

Issue Overview: I have successfully implemented a cascading dropdown feature for Country and State using Jquery and Json. Everything is functioning as expected except for the validation aspect. When I open the view, if I click on the create button without ...

The Angular scope remains stagnant even after applying changes

Having trouble updating a variable in the ng-repeat loop <div ng-controller="MapViewCtrl"> <a class="item item-avatar" ng-href="#/event/tabs/mapView" > <img src="img/location.jpg"/> <span cl ...

Struggling to retrieve integer values from a JSON object array

I'm currently working on a function to iterate through an array of objects retrieved from the server. When I console.log the response, this is the structure I see. https://i.sstatic.net/ErOps.png This is the JavaScript function I've created for ...

Developing a feature where user-entered data can be saved to a database with the click of a button

Seeking guidance on integrating a "Request" button into a search box. The user input in the search bar should be stored in the database upon clicking the request button. Currently working with CodeIgniter for this project. ...

When multiple checkboxes are selected, the corresponding form fields will be automatically filled with shared information

When the user checks multiple checkboxes, corresponding form fields should appear based on the checkboxes selected. For example, if the user checks both the flight and hotel checkboxes, the fields for full name and last name should be displayed, while othe ...

Is it a not-so-great idea to use a combination of Bootstrap CSS and Custom CSS for styling

Is it considered bad practice to apply custom CSS on top of standard Bootstrap CSS for a button? Should I completely remove Bootstrap and use only custom CSS? If so, what is the trade-off in terms of performance? Another web developer mentioned that addit ...

Exploring the ways to retrieve the returned Dynamic scope in AngularJS

There's a specific need I have - I require a single AngularJS function that can dynamically return the scope variable based on an input parameter. When it comes to controller functions, I've come across examples of how to achieve this dynamic sco ...

Incorporate various pieces of information into an object

Hey everyone, I need some help with my ServiceNow code. I have a JavaScript doubt regarding it. I am attempting to display data in a marquee. <div> <marquee><b ng-repeat='val in data.arr'><label>{{val.display_field}}</ ...

Guide on creating a dynamic line segment in real-time with three.js

Just delving into the world of Three.js and aiming to replicate the drawing technique seen in Microsoft Paint for creating line segments. My goal is to capture the coordinates of a point onMouseDown and continue extending a line with onMouseMove until re ...

Access the properties of a JSON object without specifying a key

I am dealing with a collection of JSON arrays structured like this: [ { team: 111, enemyId: 123123, enemyTeam: '', winnerId: 7969, won: 1, result: '', dat ...

Convert a list into nested JSON items by utilizing the getJSON function

Below is an example of a JSON object: {"sessions":[ { "totalusers":"2", "Users": [ { "id": 1, "name": "abc" }, { "id": 2, "name": "def" } ] } ]} Here is the corresponding HTML structure: <div> ...

Utilizing PHP variables to dynamically assign names to radio input tags, and then extracting their values using jQuery or JavaScript

I am facing an issue with my PHP file that generates radio buttons based on unique pets ids. The variable $idperro is constantly changing to distinguish the set of radio buttons. My goal is to insert the value inside the p tag. Here's the PHP code sn ...

Issues with compilation arise in Angular5 application due to CSS import errors stemming from a corrupt library

Currently working on an application using the latest Angular version. I recently imported a library for a component, but it has caused more issues than assistance. Despite that, I am still encountering compilation errors and reluctant to start over with a ...

Adjusting Font Size of Menu BarORModifying

I'm currently using WordPress to build my website. If you'd like to take a look, here is the link: I'm trying to make the font size smaller to accommodate more menu bars on the site. Any suggestions on how I can achieve this would be great ...

Create a wait function that utilizes the promise method

I need to wait for the constructor() function, which contains an asynchronous method handled by Promise. My goal is to wait for two asynchronous methods within the constructor, and then wait for the constructor itself. However, my code is throwing an err ...

Create a resizable textarea within a flexbox container that allows for scrolling

Hey there! I'm struggling with a Flexbox Container that has three children. The first child contains a textarea, but it's overflowing beyond its parent element. Additionally, I want to make the content within child 2 and 3 scrollable. I've ...

Steps for Filling a List Box (combo box) with Data from a Multi-Dimensional Array

As a student learning JavaScript, I have an assignment due tonight and am facing challenges with populating a List Box (combo box) from a Multi-Dimensional Array. After working on the code multiple times, I managed to create a multi-dimensional array that ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

Using Angular's $q service in the run block

I have a scenario where I need to load data from local files using the global loadJSON function (though it's not mandatory, it's recommended). Once the data is loaded from all the documents, I want to print the string 'i ve loaded'. T ...

Issue with Material UI components failing to return an HTMLElement reference

When working with certain libraries that require the ref prop to return an HTMLElement, I have noticed that 99% of MUI components do not fulfill this requirement. What am I missing? How can I obtain a reference to the root element of a component? import R ...