Tips for extracting the values of multiple input fields in JavaScript and displaying them on a webpage

I want to collect all the values from input fields and display them on the website.

Check out my code snippet below:

var button = document.querySelector("button");
button.addEventListener("click", function() {

  var inputs = document.querySelectorAll("input").value;
  for (i = 0; i < inputs.length; i++) {
    inputs[i];
  }

  var output = document.getElementById("output");
  output.innerHTML = "Here are the values: " + inputs;
});
<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>


<button>Check</button>
<div id="output"></div>

Answer №1

When you use the expression

document.querySelectorAll("input").value;
, it does not give you the concatenated values of all selected inputs.

Instead, you can create a new variable and append the values to it inside a for loop like this:

inputsAppended += inputs[i].value;

Then, you can display the combined value using:

output.innerHTML = "Combined Value: " + inputsAppended;

var button = document.querySelector("button");
button.addEventListener("click", function() {
  var inputsAppended = "";
  var inputs = document.querySelectorAll("input");
  for (i = 0; i < inputs.length; i++) {
    inputsAppended += inputs[i].value;
  }

  var output = document.getElementById("output");
  output.innerHTML = "Combined Value: " + inputsAppended;
});
<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>


<button>Check</button>
<div id="output"></div>

Answer №2

let submitButton = document.querySelector("button");
submitButton.addEventListener("click", function() {

  let numberInputs = document.querySelectorAll("input");
  for (i = 0; i < numberInputs.length; i++) {
  let result = document.getElementById("result");
  
  result.innerHTML += numberInputs[i].value;
  }

  
});
<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="50">
</div>


<button>Submit</button>
<div id="result"></div>

Answer №3

This method provides a straightforward way to display each number on a separate line:

let button = document.querySelector("button");
button.addEventListener("click", function() {
  // Loop through all input fields, gather their values, and concatenate them with line breaks
  document.getElementById("output").innerHTML =
 [].slice.call(document.querySelectorAll("input")).map( input => input.value ).join( "<br>" );
});
<div>
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
  <input type="number" min="1" max="49">
</div>


<button>Check</button>
<div id="output"></div>

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

The onbeforeunload event is activated in the parent page when it is specified in the child page

Seeking a way to activate the window.onbeforeunload method when a user attempts to refresh the browser, and display a message to prompt them to save their current work before leaving. I am currently working on an AngularJS application. Here is the URL of m ...

The code is running just fine when tested locally, but it seems to encounter an issue when accessed remotely, yielding

Currently, I am in the process of developing a dual twin setup using a Raspberry Pi. The goal is to simulate a continuous transmission of body temperature data, which is then sent to a server that stores the information in a MongoDB database. Everything fu ...

How can one pass req.validationErrors() from the backend to the frontend with Express Validator?

Hello and thank you for taking the time to read this. I am currently trying to implement express-validator in my project. It's working well as it blocks posts if, for example, the name input is empty. However, I'm struggling to display the error ...

The process of passing parameter values by function in useEffect

Hi everyone, I hope you're all doing well. I'm currently facing an issue with trying to retrieve data from my API using the post method. The problem is that I can't use useEffect in any parameter. So, my workaround is to pass the data throug ...

Angular ng-show does not seem to evaluate properly

After receiving the JSON array object below: "Tools": [ { "name": "Submit a Claim", "position": 1, "isOn": true, "alert": null }, { "name": "My Recurring Claims", "position": 2, "isOn": true, "alert": null }, { "name": "Online Enrollment ...

Issue: Module '@angular/compiler' not found

After downloading an angular template, I encountered an issue while running "ng serve": Cannot find module '@angular/compiler' Error: Cannot find module '@angular/compiler' ... I tried various solutions found on the internet, incl ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

Incorporating Javascript .click() with Python Selenium Webdriver for Enhanced Script Functionality

Having trouble incorporating Javascript code into my Python Selenium script. The ".click()" method in Javascript is more efficient than Selenium. I need to translate this Javascript into Python, but I'm not familiar with JS : const MyVariable= $(&quo ...

Struggling to get the knockout js remove function to function properly within a nested table structure

I've been encountering issues while trying to eliminate the formulation elements with the 'Delete comp' link. I can't seem to figure out why it's not functioning as expected. Moreover, the 'Add another composition' link o ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...

What could be causing my file input to appear misaligned?

Can anyone assist me with a strange issue I am facing? Despite using inspect element on my file input and it appearing in the correct place, it does not function as expected. To see for yourself, visit oceankarma.co and click on 'Post' at the top ...

Update various components within a container

I have incorporated a function that automatically loads and refreshes content within a div every 10 seconds. Here is the script: $(function () { var timer, updateContent; function resetTimer() { if (timer) { window.clearTimeout(timer); ...

Retrieve childNodes of the Select All input using jQuery from the container node with the class name "container"

I am trying to retrieve the text value of all the childNodes within the container of the corresponding input when the Select All checkbox is checked. Currently, my code captures the text inside each input label. However, it only logs the label (e.g. &apos ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Show the helper text when a TextField is selected in Material UI

I would like the error message to only show up when a user clicks on the TextField. Here's my code: import React, { useState, useEffect } from 'react'; import { TextField, Grid, Button } from '@material-ui/core'; const ReplyToComm ...

Fade out the div element when clicked

For my game project, I needed a way to make a div fade out after an onclick event. However, the issue I encountered was that after fading out, the div would reappear. Ideally, I wanted it to simply disappear without any sort of fade effect. Below is the co ...

Customize Bottom Navigation Bar in React Navigation based on User Roles

Is it possible to dynamically hide an item in the react-navigation bottom navigation bar based on a specific condition? For example, if this.state.show == true This is what I've attempted so far: const Main = createBottomTabNavigator( { Home: { ...

Encapsulating the React Material-ui Datepicker and Timepicker OnChange event callback functionging

I'm new to React and currently incorporating Material-UI into my project for additional UI components. I've noticed some repetitive code that I'm finding difficult to refactor due to constraints within a Material-UI component's implemen ...

Exploring the relationship between React component inheritance and asynchronous requests

I'm struggling to comprehend why this isn't functioning var link = window.location.href; var array = link.split('/'); var sub = array[array.length-1]; console.log(sub); var name; var posts; var upvotes; var ProfileFiller = React.creat ...

Getting values from a JSON array in Swift 4 - a step-by-step guide

I have the following code snippet written in Swift 4 using Alamofire: Alamofire.request("http://xxxx.pl/id=1", method: .get, parameters: nil) .responseJSON { response in let jsonResponse = JSON(response.result.value!) let resData = jsonRespon ...