What are some ways that we can enhance each other's value?

I am currently delving into the realm of Java-script, with the goal of creating an input field for numbers. My vision is to have a scenario where when a user enters a number in the input field, my script will display it in a paragraph or another text field. Subsequently, if the user fills in another number in the initial text field, the script should calculate the sum of the two values together.

Is it feasible to achieve something like this?

var number = document.getElementById("numInput");
var result = document.getElementById("numOutput");

number.onchange = function() {calculate()};

function calculate(){

  result.innerHTML = number.value + " + " + "next value" + " + " + "and so on";
  result.style.display = 'block';
}
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="script.js" async></script>
  </head>

  <body>


    <input type="text" id="numInput">
    <br>
    <p id="numOutput"></p>


  </body>
</html>

Answer №1

To calculate the sum of a series of numbers, you can create a variable to store the total sum and update it as you input new values.

var number = document.getElementById("getalInput"),
    resultaat = document.getElementById("getalOutput"),
    sum = 0;                     // initializing sum variable

number.onchange = calculatie;    // assigning calculation function to onchange event

function calculatie(){
  sum += +number.value || 0;     // add input value to sum or zero for non-numeric inputs
  resultaat.innerHTML = sum;
}
<input type="text" id="getalInput"><br>
<p id="getalOutput"></p>

Answer №2

Is this how you want it?

let number = document.getElementById("numberInput");
    let result = document.getElementById("numberOutput")

    number.onchange = function() {calculate()};

    function calculate(){
      if(!result.innerHTML.trim()){
        result.innerHTML = number.value;
      }else{
        result.innerHTML +=  " + " + number.value;
      }
      number.value = '';
      result.style.display = 'block';
    }
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="script.js" async></script>
  </head>

  <body>


    <input type="text" id="numberInput">
    <br>
    <p id="numberOutput"></p>


  </body>
</html>

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

observable arrays in knockoutjs

To simplify the problem I'm facing, let's consider this example: var ViewModel = function() { this.self = this; self.test = ko.observableArray([]); self.test2 = ko.observableArray([]); self.test2.push('1'); self.test.push({ 'f ...

Unable to implement multiple draggable inner objects using Angular 5 and dragula library

After struggling for the past few days, I can't seem to get it to work... Here is a brief explanation of my issue: In this example, I have an array of objects structured like this: public containers: Array<object> = [ { "name": "contain ...

Toggle between two different functions

Embarking on my journey with HTML, JavaScript, and coding in general, I aim to create a website as part of my learning experience. This website will focus on wedding films and clips. My vision includes a side menu with a menu button (three horizontal line ...

Engaging 3D Object with JavaScript Interactivity

I'm currently working on a project for my HCI assignment where I need to create an interactive Sphere using JavaScript. However, I am new to JavaScript and Three.js. My goal is to have the sphere display statistics of a specific subject when clicked. ...

Using JavaScript regex to match repeating subgroups

Can a regular expression capture all repeating and matching subgroups in one call? Consider a string like this: {{token id=foo1 class=foo2 attr1=foo3}} Where the number of attributes (e.g. id, class, attr1) are variable and can be any key=value pair. C ...

Encountering an issue while invoking the helper function in Vuejs

Main view: <script> import { testMethod1 } from "../helper"; export default { methods: { init(){ console.log("Res:", testMethod1()); } } } </script> Helper: import DataService from "../services/data. ...

Discovering the correct index of the optgroup element within selected options

When the "obj" object receives the "optgroup" elements as parameters and their corresponding options as values, an issue arises when options from both optgroups are selected. In this case, all option values are returned from the first optgroup and the prev ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

I'm experiencing issues with the autofocus attribute when using the bmd-label-floating feature in Bootstrap Material Design version 4.1.1

Issue with Bootstrap-JavaScript Autofocus Attribute Upon page load, the autofocus attribute fails to trigger the addition of the is-focused class by the Bootstrap-JavaScript for the corresponding (bmd-)form-group. https://i.sstatic.net/2V374.png <fie ...

Identifying the moment an external swf file has finished loading

My JavaScript code is responsible for loading external swf files by adding the "object" and "embed" tags after the page has finished loading. I am looking for a way to detect when the swf file has been fully loaded so that I can handle this event appropr ...

Tips for showcasing a string value across various lines within a paragraph using the <br> tag for line breaks

I'm struggling to show a string in a paragraph that includes tags to create new lines. Unfortunately, all I see is the br tags instead of the desired line breaks. Here is my TypeScript method. viewEmailMessage(messageId: number): void { c ...

Is there a way to automatically reset an Angular scope variable when an HTML tag is executed?

Hi, I have a variable linked to my scope, $scope.isValid = { incorrectPhone: false } I am using a span to show a message when the variable becomes true ... <form name="myForm"> <span ng-if="isValid.incorrectPhone && myForm.$submitted" ...

Sending an Ajax request following validation with jQuery

After successfully validating a form, I attempt to make an ajax request. Strangely, if I remove the , after url: 'loginprivate.php', the PHP code functions properly but the validation does not. On the other hand, if I add the ,, the validation wo ...

Tips for identifying incognito mode and launching a fresh tab within an already open incognito window

I may not be a professional developer, but I created a Chrome extension app. You can check it out here: Link to Chrome Extension This app currently adds a context menu and opens a new tab in Chrome. However, one of my users has asked me to make the app wo ...

Utilize nested keys to reduce an array of objects in JavaScript

I am facing a challenge with an array that contains a list of JavaScript objects. My goal is to utilize the reduce function to transform it into a single object with nested key groupings. This is how the initial array appears: [ { "product": 1, ...

Flask Session Persistence Issue: Postman Successful, Javascript Fails

Developing a Flask server to facilitate communication between backend Python functionality and Javascript clients on the web has been my recent project. I am trying to harness Flask's `session` variable to retain user-specific data throughout their in ...

The Javascript alert is displaying twice in Internet Explorer

My file validation function is set up to only allow the uploading of xls files, and it works properly by displaying an error message if a non-Excel file is uploaded. However, there is an issue with the alert firing twice in IE. Here is my code: function ...

Tips for accessing every "results" (parameters) from an API

Here is the response I received after making an API call in my attempt to retrieve each "bloc" result using a .forEach. const app = express(); const axios = require('axios') jobList = []; app.get('/getAPIResponse', function(req, res) ...

Ways to obtain the <a> using the title attribute

Is there a way to remove 3 classes from a specific <a> element that is dynamically generated? The only constant is the title. How can I locate an element based on its title? I've searched online but haven't found exactly what I'm looki ...

"Incorporating JavaScript into Website, Navigating Browser Discrepan

Upon designing a simple webpage that requires minimal JavaScript functionality, I encountered varying behaviors across different browsers depending on the placement of the <script> tag. In Chrome (65) and Firefox (59), the position of the <script ...