Is there a way to modify initialValue's value following every iteration?

I need assistance in changing the value of initialValue after each operation. For example, if I input 1000, the output should be 11,000 (10,000 + 1,000). Then, if I subtract and input 2000, the output should be 9,000 (11,000 - 2,000). Can anyone provide guidance on how to solve this issue?

// Constructor Function
function Compute(initialNum, numOne) {
this._initialNum = 10000;
this._numOne = numOne;

this.addNum = function() {
this._initialNum = +this._initialNum + +this._numOne;
return this._initialNum;
};

this.minusNum = function() {
this._initialNum = +this._initialNum - +this._numOne;
return this._initialNum;
};
}

// Body tag JavaScript
var tblResult = document.getElementById("tblResult");
var personList = [];

function printResult() {
        var display = "";
        var initialValue = parseInt(document.getElementById("persistedResult").value);
        var rdoAdd = document.getElementById("rdoAdd");
        var rdoMinus = document.getElementById("rdoMinus");
        var numOne = parseInt(document.getElementById('txtNumOne').value);
        var objCompute = new Compute(initialValue, numOne);
        personList.push(objCompute);

        console.log(personList);
        var newValue = 0;
        for(var i = 0; i < personList.length; i++) {
            if(rdoAdd.checked) {
                newValue = personList[i].addNum();
                display = "<tr>";
                display += "<td>" + (newValue) + "</td>";
                display += "<tr>";
                tblResult.innerHTML += display;
            resetx();

            } else if(rdoMinus.checked){
                newValue = personList[i].minusNum();
                display = "<tr>";
                display += "<td>" + (newValue) + "</td>"; 
                display += "<tr>";
                tblResult.innerHTML += display;
            resetx();
        }
    }
    document.getElementById("persistedResult").value = newValue;
}
function resetx() {
document.getElementById('txtNumOne').value = "";
document.getElementById("rdoAdd").checked = false;
document.getElementById("rdoMinus").checked = false;
}
<!DOCTYPE html> 
<html>
<head>
<title></title>
</head>
<body>

<input type="hidden" id="persistedResult" value="10000" /><br><br>
<input type="radio" id="rdoAdd" name="rdo">Add<br><br> // Radio button for Add
<input type="radio" id="rdoMinus" name="rdo">Minus<br><br> // Radio button for Subtract
<input type="text" id="txtNumOne"><br><br> 
<button onclick="printResult()">Compute</button><br><br>

<table border="1px">
<th>Result</th>

<tbody id = "tblResult">

</tbody>
</table>

</body>
</html>

I want to change the value of initialValue after each run Ex: If I type 1000, this will give the output as 11,000 (10000 + 1,000), and I minus and I type 2000, this will give the output as 9,000 (11,000 - 2,000). Can somebody help me regarding to my problem.

function printResult() {
        var display = "";
        var initialValue = 10000;
        var rdoAdd = document.getElementById("rdoAdd");
        var rdoMinus = document.getElementById("rdoMinus");
        var numOne = parseInt(document.getElementById('txtNumOne').value);
        var objCompute = new Compute(initialValue, numOne);
        personList.push(objCompute);

        console.log(personList);

        for(const person of personList) {
            if(rdoAdd.checked) {
                display = "<tr>";
                display += "<td>" + (person.addNum()) + "</td>";
                display += "<tr>";
                tblResult.innerHTML += display;
            resetx();

            } else if(rdoMinus.checked){
                display = "<tr>";
                display += "<td>" + (person.minusNum()) + "</td>"; 
                display += "<tr>";
                tblResult.innerHTML += display;
            resetx();
        }
    }
}

// Constructor Function
function Compute(initialNum, numOne) {
this._initialNum = initialNum;
this._numOne = numOne;


this.addNum = function() {
    this._initialNum += this._numOne;
    return this._initialNum;
};

this.minusNum = function() {
    this._initialNum -= this._numOne;
    return this._initialNum;
};
}

Answer №1

To handle the stateless nature of HTTP and perform operations on multiple actions, it is necessary to store the result of each action somewhere. One simple approach is to create a hidden field in the HTML page. This field can be initialized with a value of 10000 when the page loads and then update its value after each action.

Suppose you have a hidden field in your HTML like this:

<input type=“hidden” id=“persistedResult” value=“10000” />

Here's an updated version of your printResult method:

function printResult() {
        var display = "";
        var initialValue = parseInt(document.getElementById(‘persistedResult’).value);
        
        var rdoAdd = document.getElementById("rdoAdd");
        var rdoMinus = document.getElementById("rdoMinus");
        var numOne = parseInt(document.getElementById('txtNumOne').value);
        
        var objCompute = new Compute(initialValue, numOne);
        personList.push(objCompute);

        console.log(personList);
        var newValue = 0;
        for(var i = 0; i < personList.length; i++) {
            if(rdoAdd.checked) {
                newValue = personList[i].addNum();
                display = "<tr>";
                display += "<td>" + (newValue) + "</td>";
                display += "<tr>";
                tblResult.innerHTML += display;
            resetx();

            } else if(rdoMinus.checked){
                newValue = personList[i].minusNum();
                display = "<tr>";
                display += "<td>" + (newValue) + "</td>"; 
                display += "<tr>";
                tblResult.innerHTML += display;
                resetx();
            }
        }
        document.getElementById(‘persistedResult’).value = newValue;
    }

Note: This is a basic example demonstrating data persistence. In practice, data would typically be persisted on a server.

The provided code handles scenarios with only one person in the list. If you want to work with an array of persons, you will need to enhance the logic accordingly.

Answer №2

  var valueEl = document.getElementById('value');
  var addEl = document.getElementById('add');
  var resultEl = document.getElementById('result');
  var calculateEl = document.getElementById('calculate');
  var initialValue = 1000;

  function displayCalculation(value) {
    var liEl = document.createElement("li");
    liEl.innerHTML = value;
        resultEl.appendChild(liEl);     
  }

  function handleCalculateClick() {
    var operand = addEl.checked ? 1 : -1;
    var val = +valueEl.value * operand;
    initialValue += val
    displayCalculation(initialValue);
  }

  calculateEl.addEventListener('click', handleCalculateClick)
  displayCalculation(initialValue);

Link to jsFiddle

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

Is there a way to automatically close one menu when another is opened by clicking?

When all other search results have failed to solve my issue, I resort to posting my own question. My problem involves opening hidden submenus in a website's main menu. However, when I open multiple submenus, they just stack above each other. Ideally, ...

Issues arise when attempting to manipulate the DOM with ng-view in AngularJS

Apologies for not providing the code due to its length. I have a simple application with a single module, controller, and ng-view/routProvider. In my controller, when I use console.log(angular.element('div').length), it correctly shows that ther ...

Customize your payment with a PayPal button tailored to your desired price

I've been tasked with creating a dynamic PayPal button that can receive different values based on user choices. The website has so many options that creating separate buttons for each choice doesn't seem feasible. I've tried researching solu ...

Encountering the error message "Unable to access property 'addEventListener' of null while trying to manipulate innerHTML"

Currently, I am utilizing innerHTML to include certain elements and a wrapper around them. for (i = 0; i < arr.length; i++) { b.innerHTML += "<div class='wrapper'><div class='col-4'>" + arr[i].storeID + "</div> ...

Obtaining an array element from mongoose at the corresponding index of the query

My Schema looks like this: const PublicationSchema = mongoose.Schema({ title: { type: String, required: true }, files:[{ contentType: String, data: Buffer, name: String }] }) I am attempting to re ...

When a user hovers over an li element, jQuery will dynamically adjust the width of the element based

<ul class="level0"> <li class="level1" id="cat2441"></li> <li class="level1" id="cat2450"></li> <li class="level1" id="cat2455"></li> </ul> <div class="alles-zwei" id="new-cat2441"></div> <div ...

Creating operations in Angular using the Model View Controller (MVC)

What is the procedure for performing an Add operation in MVC using Angular? var addProductModule = angular.module("addProductModule", []); addProductModule.factory("addProductService", ['$http', function ($http) { return { function savePro ...

Dealing with the hAxis number/string dilemma in Google Charts (Working with Jquery ajax JSON data)

My Objective I am attempting to display data from a MySQL database in a "ComboChart" using Google Charts. To achieve this, I followed a tutorial, made some modifications, and ended up with the code provided at the bottom of this post. Current Behavior T ...

PHP and MySQL with jQuery and AJAX combine to create a real-time news feed update system similar to Twitter

Is there a way to automate the news feed on my website so that it periodically checks for new status updates? I would like it to display a button labeled "(?) New Messages" when there are new updates, and then load only the new ones when the button is clic ...

What is the best way to display only li elements that possess a specific class utilizing javascript / jquery?

I have a bunch of li's: <ul> <li class="one"></li> <li class="one"></li> <li class="two"></li> </ul> and I want to display only the ones with the class "one" I attempted something like thi ...

How can we allocate array elements dynamically within div elements to ensure that each row contains no more than N items using only HTML and JavaScript?

For instance, if N is 3 in each row, as more elements are added to the array, the number of rows will increase but each row will still have a maximum of 3 elements. I am currently using map to generate corresponding divs for every element in the arr ...

Leveraging Vue 3 Composition API with accessors

I'm currently in the process of refactoring some of my components using the composition API. One component is giving me trouble, specifically with asynchronous state when trying to retrieve data from one of its getters. Initially, the component was u ...

Enhance jQuery event handling by adding a new event handler to an existing click event

I have a pre-defined click event that I need to add another handler to. Is it possible to append an additional event handler without modifying the existing code? Can I simply attach another event handler to the current click event? This is how the click ...

Utilizing OpenLayers3 to create a global JavaScript variable

What could be the reason for this code working? function addMap() { var view = new ol.View({ center: ol.proj.fromLonLat([29.5646, 44.1575]), zoom: 4 }); var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Til ...

Utilize React without integrating a router component

For my web application built with reactjs, I am considering creating a multi-page site rather than a single page. Should I bundle all the react code into one file and include it on every page of the application, then utilize the exposed function to render ...

Measuring the success of Vuejs app

Seeking performance metrics for a Vue application. Interested in metrics for the entire app as well as specific components. I am aware of using Vue.config.performance = true; to enable performance monitoring through dev tools, and I have considered utiliz ...

Experiencing a problem with the JavaScript loading function

An error was logged in the console SyntaxError: unterminated string literal A piece of code is supposed to display a notification $(document).ready(function () { alertify.success("Success log message"); return false; }); Despite testing the cod ...

First experience with Django Bootstrap Modal Ajax was flawless, but on the second attempt, it was not as successful

I am currently utilizing Django 2.2 in conjunction with Bootstrap. The method implemented is as follows: Triggering the opening of a modal window, User updates the data, User saves the data, Underlying table from where the window originated is updated a ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

toggle back and forth between two div elements

I am trying to create a toggle effect between two divs, where clicking on one will change its border and header color to red while the other div disappears. I have tried using an IF statement in my JavaScript code, but it is not working as expected. Can so ...