I am attempting to refresh my number using the latest value obtained from a text input field in JavaScript

I am currently working on a JavaScript program that involves updating numbers in a field based on user input. For example, if the initial number in the field is 5 and the user enters 4 in the textfield, then the field should display the total of both numbers which would be 9.

document.getElementById('btn').addEventListener('click', () => {
  console.log("Button clicked")
  var newTotal = 0
  var input = parseInt(document.getElementById('text').value)
  newTotal = input
  if (newTotal) {
    console.log(newTotal)
    newTotal += input
  }
  console.log(newTotal)
  document.getElementById('textField').innerHTML = newTotal
  document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">

Answer №1

Give this a shot, my friend. Make sure to set newTotal to 0 outside of the function. Otherwise, if it's inside the function, each time the function is called, newTotal will reset to 0 and then add the new input to itself.

Thank you.

let newTotal = 0

document.getElementById('btn').addEventListener('click', () => {
  const input = parseInt(document.getElementById('text').value)
  if (input) {
     newTotal += input
  }
  
  document.getElementById('textField').innerHTML = newTotal
  document.getElementById('text').value = ''
})
<input type="text" id="text">
<h3><span id="textField">0</span></h3>
<input type="submit" id="btn" value="Add Numbers">

Answer №2

document.getElementById('input-data')

        //Event listener for onchange event
        .addEventListener('change', () => {

            var val = document.getElementById("input-data").value;
			//Check if the input is a valid integer and display alert message
            if (isNaN(val)) { 
                document.getElementById('input-data').value = '';
                alert("Please enter a valid number");
                throw new Error("Invalid Number Entered");
            }
            //If input is a valid integer, add it to the existing value
            document.getElementById("output-field").innerHTML = 
                parseInt(document.getElementById("output-field").innerHTML) + parseInt(val);
            
            document.getElementById('input-data').value = '';
    })
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8>
    <title>Add Numbers</title>
</head>
<body>
    <input type="text" id="input-data">
    <h3><span id="output-field">0</span></h3>
</body>
</html>

Note: The throwing error and displaying alerts are not necessary.

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

Load specific options only when needed while maintaining the previously selected state

First off, check out this demo to see what I mean. I have a basic form with a dropdown field. Initially, only one option is pre-loaded and selected. The goal is to load the remaining options when the dropdown is clicked. This functionality works fine, exc ...

Creating a Dynamic Ball Animation in JavaScript using Canvas

What should I tweak in the code to make the ball bounce upward at the beginning? I am completely lost here and have experimented with numerous ideas without success. I feel like I must be overlooking something simple. It seems like the key part of the co ...

Tips to avoid conflicts between endpoints when building a REST API in an Express application

I am currently working with a REST API in an Express application to retrieve orders. http://localhost:2000/api/orders/chemists?orderBy=date&startDate=date1&endDate=date2 http://localhost:2000/api/orders/chemists?orderBy=chemist&startDate=date ...

Is it time to use the JavaScript preload() function?

When I initially select a radio button, I experience a brief freezing effect. However, upon selecting them a second time, everything operates smoothly. I suspect this is due to the radio buttons being stored in the browser cache. Is there a way to preloa ...

Adjust background image size to fit the screen, not just the content

Whenever I set the background image for each page using the following JavaScript code, var imageUrl = 'url(' + imageUrl + ') top left no-repeat fixed'; $('body').css({ 'background': imageUrl }); I also add ...

I'm seeking assistance on how to utilize recursion to traverse through every element within the DOM

My current assignment requires me to use recursion in JavaScript to navigate through every element in the DOM. For each body element, I must determine if it is an element node, and if so, add a child node to it. Here is what I have implemented in my JavaSc ...

Exploring VueJS watchers: How to get started?

Struggling to grasp the concept of Watchers in VueJS, particularly when trying to implement them for tracking tab changes and resetting values. Even though I have set up a watch with parameters like `oldValue` and `newValue`, their usage remains unclear to ...

Ways to organize information based on the date

Is there a way to organize data from an API in chronological order? Here is an example of how it should be displayed: <table> <tr> <th>2017-02-17</th> </tr> <tr> <td>some date</td&g ...

The code is functioning well on Chrome, Firefox, and Microsoft Edge; however, it seems to encounter issues when running on Safari

I've been working on a website for my client that works perfectly fine in Chrome, Firefox, Microsoft Edge, and even Internet Explorer :P. However, I'm facing some issues with Safari. Here's a snippet of the code I used: <html> <hea ...

Unable to view Bootstrap Icons in Gulp 4

I recently integrated the new bootstrap icons npm package into my project using Gulp 4, the latest version. Everything was installed successfully and was working smoothly. However, I encountered an issue when trying to declare the icon in my index.html fi ...

Learn the steps to emphasize the first row of a material table using React

Within my react application, there is a material table that I have styled using the following code snippet: <MaterialTable options={{ exportButton: true, exportAllData: true, pageSize: 5, pageSizeOptions: [5, 10, 15 ...

Discover the positions of the y-axis tick marks with d3.js

I have been working on creating an SVG visualization using d3.js (specifically version 3 of d3 in PowerBI) and I am encountering difficulties in aligning my data points and fixed lines with the correct y-axis tick markers. When there are 8 axis points, th ...

Find the differences between two arrays of objects and create a new array containing only the matching items

Currently, I am executing two GET requests. One to retrieve data from my database and another from an external API. The database array consists of player information with 'Active' statuses set to either true or false (as the front-end feature al ...

Cloud function -> time stamps evaluation

I've been working on a cloud function to delete items in the "links" collection that have an end time older than the current timestamp. Although my function runs without any errors, it's not deleting the items as expected and is causing me quite ...

Whenever a new entry is made into the textfield, the onChange feature triggers a reset on the content within the textfield

I'm experiencing an issue while creating a SignUp authentication page with Firebase. Every time I try to input text in the text field, it gets reset automatically. I have been unable to identify the root cause of this problem. It seems to be related t ...

Converting complex mongodb data structures into Backbone.js Models/Collections

Within my mongodb database, I store collections comprising of documents and embedded documents at the posts and comments levels. One example is a post document that includes two comments as embedded documents. { "__v" : 0, "_id" : ObjectId("502d7b ...

How can you choose all objects that are similar within an array, based on specific keys?

Is there a way to filter an array to find all objects that share similarities in certain keys, even if the values of those keys are unknown? Consider having an object structured like this: let list = [ { name: 'Adam', age: '10', u ...

iterate through all the items in the radioButton collection

Hello, I am looking to iterate through this object and display checkbox values along with their indices. data: [ { key1: 'last 6 months' }, { key2: 'last 30 days' } ] I would like to creat ...

Tips for customizing the appearance of a label when a MUI Radio Button is selected

Hello everyone, I am attempting to customize the label text color of a radio button to turn blue when selected. https://i.stack.imgur.com/btSc2.jpg HERE IS THE CODE FOR MY MUI BUTTON SO FAR import * as React from "react"; import Radio from &quo ...

What could be causing me to have to click the button twice in order to view my dropdown list? Any suggestions on how to

I am facing an issue where I have to click twice on the "Action" button in order to see my dropdown list. How can I resolve this? Is there a way to fix it? $(document).ready(function() { $(".actionButton").click(function() { $dropdown = $("#cont ...