Can the value in a JavaScript object be updated dynamically when a button is clicked?

In my JavaScript code, there is an object named annualPlan.

Whenever a user submits the HTML form for a specific month, I aim to update the value in the object for that particular month accordingly.

For instance, if someone submits August 21 and 200, I want the value of pAug to be 500.

However, if the same person re-submits August 21 and 500, I intend for pAug to revert back to 200.

The chunk of code below showcases my endeavor to accomplish this task (even though it felt more like attempt number 100!).

What are your thoughts on this approach?

var planMonth;
var planAmount;




//generate a unique ID based on the current time when the form is submitted
var today = new Date();
var FullDate = today.getDate() + "-" + (today.getMonth() + 1); //adjusting start month from 0 by adding 1
var time = today.getHours() + ":" + today.getMinutes();
var dateTime = FullDate + " " + time


var annualPlan = {
  pJan: 0,
  pFeb: 0,
  pMarch: 0,
  pApril: 0,
  pJune: 0,
  pJuly: 0,
  pAugust: 0,
  pSept: 0,
  pOct: 0,
  pNov: 0,
  pDec: 0,
};

const addPlan = function(ev) {

  ev.preventDefault();
  let planUpdate = {

    id: dateTime,
    Month: document.getElementById("PlanMonth").value,
    Amount: document.getElementById("PlanSave").value,
  }

  annualPlan.push(planUpdate);
  document.querySelector("form").reset();

  //console.log(annualPlan);
}

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById("button").addEventListener("click", addPlan);
});
/* PAGE STRUCTURE START */

body {
  padding-left: 150px;
  padding-right: 150px;
  font-family: Georgia, 'Times New Roman', Times, serif;
  font-size: 18px;
}

#inputarea {
  margin-top: 100px;
}

label {
  display: inline-block;
  padding-bottom: 8px;
  font-size: 22px;
  font-family: Georgia, 'Times New Roman', Times, serif;
}

input {
  padding: 10px 20px;
  font-size: 18px;
  letter-spacing: 2px;
}

#formSection {
  padding-top: 30px;
}


/* PAGE STRUCTURE END */


/* FONT STYLING START */

#inputarea h3 {
  text-decoration: underline;
  color: #334058;
  font-size: 30px;
}


/* NAVIGATION AREA START */

* {
  -webkit-transition-property: all;
  transition-property: all;
  -webkit-transition-duration: .2s;
  transition-duration: .2s;
  -moz-transition-timing-function: cubic-bezier(100, 50, 21, 6);
  transition-timing-function: cubic-bezier(100, 50, 21, 6);
  -moz-transition-property: all;
  -moz-transition-timing-function: cubic-bezier(100, 50, 21, 6);
}

.style-1 {
  text-align: center;
  margin-top: 40px;
}

.btn {
  color: #fff;
  background: #3399cc;
  padding: 20px 40px;
  text-decoration: none;
  letter-spacing: 2px;
  text-transform: uppercase;
}

.btn:hover {
  border: none;
  background: rgba(0, 0, 0, 0.4);
  background: #fff;
  padding: 40px 40px;
  color: #334058;
}


/* NAVIGATION AREA END */
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grow Your Wealth</title>
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link rel="icon" href="images/fav.ico">

</head>
<!-- Navigation Start -->

<nav class="style-1">
  <a href="index.html" class="btn">Home</a>
  <a href="appPage.html" class="btn">App Page</a>
</nav>

<!-- Navigation End -->

<section id="inputarea">
  <h3 id="section-header">Plan Input Area</h3>

  <form onsubmit=>
    <div id="formSection">
      <label for="PlanMonth">Month</label><br>
      <input type="month" name="PlanMonth" id="PlanMonth" value="2021-08">
    </div>
    <div id="formSection">
      <label for="PlanSave">Planned Saving for Month</label><br>
      <input type="number" name="PlanSave" id="PlanSave" value="200"><br><br>
    </div>
    <div id="formSection">
    </div>
    <input type="submit" value="submit" id="button">
  </form>



</section>



<!-- JS File -->
<script src="js/app.js"></script>
</body>

</html>

Answer №1

First, extract the month value from the input and then match it with the corresponding month.

For example, if the input date is 2021-08.

  1. Extract the month as 08.
  2. Based on your month names, 08 corresponds to pAugust.
  3. Adjust the month index to start from 0, so 8-1 becomes 7.
  4. Add the existing value of that month in the yearly plan using annualPlan[month] and increment it by the value of amount.

var planMonth;
var planAmount;


//create a custom ID value with the current time of form submit
var today = new Date();
var FullDate = today.getDate() + "-" + (today.getMonth() + 1); //getMonth method starts from 0. Add 1 to get real month.
var time = today.getHours() + ":" + today.getMinutes();
var dateTime = FullDate + " " + time


var annualPlan = {
  pJan: 0,
  pFeb: 0,
  pMarch: 0,
  pApril: 0,
  pMay:0,
  pJune: 0,
  pJuly: 0,
  pAugust: 0,
  pSept: 0,
  pOct: 0,
  pNov: 0,
  pDec: 0,
};

function findmonth(month){
// Get the month
month =  month.split('-')[1]
// Geta all the months
let months = Object.getOwnPropertyNames(annualPlan)
// Return the month according to the object annualPlan
return months[parseInt(month)-1]
}
const addPlan = function(ev) {

  ev.preventDefault();
  let planUpdate = {

    id: dateTime,
    Month: document.getElementById("PlanMonth").value,
    Amount: document.getElementById("PlanSave").value,
  }
  // Get the existing value of the month
  let existingVal = annualPlan[findmonth(planUpdate.Month)];
  // Add the new value and update it to the obj
  annualPlan[findmonth(planUpdate.Month)] = parseInt(existingVal) +  parseInt(planUpdate.Amount)
  console.log(annualPlan)
  document.querySelector("form").reset();

  //console.log(annualPlan);
}

document.addEventListener('DOMContentLoaded', () => {
  document.getElementById("button").addEventListener("click", addPlan);
});
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Grow Your Wealth</title>

  <link rel="icon" href="images/fav.ico">

</head>
<!-- Navigation Start -->

<nav class="style-1">
  <a href="index.html" class="btn">Home</a>
  <a href="appPage.html" class="btn">App Page</a>
</nav>

<!-- Navigation End -->

<section id="inputarea">
  <h3 id="section-header">Plan Input Area</h3>

  <form onsubmit=>
    <div id="formSection">
      <label for="PlanMonth">Month</label><br>
      <input type="month" name="PlanMonth" id="PlanMonth" value="2021-08">
    </div>
    <div id="formSection">
      <label for="PlanSave">Planned Saving for Month</label><br>
      <input type="number" name="PlanSave" id="PlanSave" value="200"><br><br>
    </div>
    <div id="formSection">
    </div>
    <input type="submit" value="submit" id="button">
  </form>



</section>
</body>

</html>

Answer №2

It seems like there might be some errors in the code you provided. Here are a few suggestions that may help you troubleshoot your issue.

<button onClick={performAction}>Click Me</button>

...

const info = {
  // place values here
}

const performAction = () => {
  info.sample = // add new content here
}

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

Can an element on a webpage be dynamically assigned an ID using JavaScript or PHP?

Is it possible to dynamically set the ID of an element during runtime of a webpage? Let's consider this scenario - <body id="body1"> Now, I would like to dynamically set the ID of this "body" element using a variable value in PHP code. Is som ...

Inability to assign a value to an @input within an Angular project

I recently started using Angular and I'm currently trying to declare an input. Specifically, I need the input to be a number rather than a string in an object within an array. However, I'm encountering difficulties and I can't figure out wha ...

Unable to retrieve options from a particular select box

Utilizing cheerio and nodejs to scrape all the countries listed on a website, I have implemented the following code: const rp = require('request-promise'); const cheerio = require('cheerio'); const options = { uri: 'https://u ...

Implementing bootstrap columns while displaying individual components one after the other

Here is the html code I am currently working with: <label>Search:</label> <input type="text" id="list_search" class="form-control col-8"> <button class="btn btn-info col-2">Search</button> It's interesting to note that ...

How can I make a method in VueJS wait to execute until after rendering?

There is a button that triggers the parse method. parse: function() { this.json.data = getDataFromAPI(); applyColor(); }, applyColor: function() { for (var i=0; i<this.json.data.length; i++) { var doc = document.getElementById(t ...

What is the best way to reload scripts each time a component is mounted?

My jQuery scripts include animation effects that need to be refreshed whenever something new is rendered on the page. However, I am facing an issue where the jQuery scripts are not being refreshed as needed. Below is my router configuration: export defau ...

What is the best way to obscure or conceal images of runners?

I am trying to figure out how to blur or hide the runner thumbnails on different streaming sites, such as Prime Video. I typically use the Amino: Live CSS Editor chrome extension or uBlock Origin to manipulate elements on websites. However, I am struggling ...

I specified Authorization Bearer in the Fetch API configuration, however, the Request Headers do not contain the necessary Authorization information

Check out the following code snippet: fetch('http://localhost:3000/tasks/', { method: 'GET', mode: 'no-cors', headers: new Headers({ 'Authorization': 'Bearer <jwt_token>' ...

The jQuery load() method may not load all elements

I've been struggling with a query issue for quite some time now. I have a Content Management System that I want to integrate into my website, but unfortunately, I am unable to use PHP includes. As an alternative, I decided to utilize jQuery instead. D ...

Offspring of the superior element resting above another element

I'm dealing with a unique situation involving the Z-INDEX property. Check out my HTML setup below. <div class="player"> <div class="player-line"> <div class="player-handle"></div> <!-- /.player-handle --> </d ...

What is causing the error message 'Unexpected use of 'location' no-restricted-globals'?

When working on my reactjs code, I encountered the following issue: const { children, location: { pathname }, } = this.props; let path = location.pathname; I am also utilizing the react router module in this component. Anyone have suggestions on how ...

The local server for handling HTTP requests has ceased to operate

Recently, I set up the NPM package along with the http server within the "server" directory. Initially, everything was functioning smoothly; however, the server abruptly ceased operating. Upon attempting to launch the local http server, an error message a ...

Can I inspect the HTML source of GWT?

How can I access the HTML source code generated by GWT? Currently, I only see the DIV with a specific ID when viewing the source. Is there a way to view the entire HTML output? Is it possible to design my table in HTML using divs and lists, then wrap it i ...

Update dynamically generated CSS automatically

Is there a way to dynamically change the CSS? The problem I'm facing is that the CSS is generated by the framework itself, making it impossible for me to declare or modify it. Here's the scenario at runtime: I am looking to target the swiper-pa ...

Including additional data to a page after each iteration in order to display the current progress

I am currently working on a loop that iterates through the lines of a text area and processes each line sequentially. However, I am facing an issue where the page becomes unresponsive until all the data has been processed. Is there a way to dynamically u ...

Encountering an issue upon pressing the 'calculate' button

Currently, I am delving into express node.js and attempting to execute a straightforward calculator code. However, whenever I click on the button, I do not receive any response, and there are no errors in my code either. I find myself a bit lost in figurin ...

What could be causing the modal to not appear when clicking on this div?

$(function() { $("#pagination a").trigger('click'); // When the page loads, trigger a click event $('body').on('click','div.well well-sm',function(){ var list = $(this); $('#myModal .modal-title').h ...

Building with bricks and mortar does not involve organizing visual content

I'm currently trying to organize some fairly large images using masonry, but the code below doesn't seem to be working. I'm using node.js with express and have installed the masonryjs package in an attempt to make it work, but that approach ...

Styling for jQuery mobile panels disappears when used on multiple pages

Currently, I am working on developing a mobile application for PhoneGap using jQuery Mobile. The app consists of multiple pages within the same HTML document. I have configured it so that all pages share the same panel, but I am facing an issue with the st ...

Is it possible to execute in a specific context using npm?

I am seeking to execute npm scripts that are executable by VuePress. For instance, I have VuePress installed and would like to run the command vuepress eject. Although I can access vuepress in my scripts, there is no specific script for eject: "scr ...