3

I'm doing JavaScript meal nutrition calculator. It is a template with 5 rows, every each row got 4 inputs, so twenty in total, type=value. Every input got different id.

Is there any way to read all inputs at the same time without duplicating "var x = document.getElementById('x').value" 20 times?

Best,

<html>
<head>
</head>
<body>
<div>
<h1>Calculator</h1>
<div>ingredient: 
<input type="number" id="x" placeholder="x">
<input type="number" id="y" placeholder="y">
<input type="number" id="z" placeholder="z">
<input type="number" id="a" placeholder="a"></div>

<button onclick="calo()" id="cal">Go</button>
<h1>Facts</h1>  
</div>
<div id="result">Result is displayed here.</div>
</body>
</html>


function calo() {
const [x,y,z,a] = [...document.querySelectorAll('input')];
document.querySelector("pre").textContent = x.outerHTML + "\n" + y.outerHTML + "\n" + z.outerHTML + "\n" + a.outerHTML;

var calculate = x + y + z + a;

document.getElementById("result").innerHTML = calculate;}

1 Answer 1

3

You can use document.querySelectorAll.

document.querySelectorAll('input')
    .forEach(input=>console.log("Id:", input.id, "Value:", input.value));

If you want the input elements declared as separate variables, you can use a destructuring assignment. Example:

const [x,y,z] = document.querySelectorAll('input');
document.querySelector("pre").textContent 
      = x.outerHTML + "\n" + y.outerHTML + "\n" + z.outerHTML;
<input type="number" id="x">
<input type="number" id="y">
<input type="number" id="z">
<pre></pre>

Sign up to request clarification or add additional context in comments.

10 Comments

How it will look like for "type=name", for 3 inputs: <input type="number" id="x"> <input type="number" id="y"> <input type="number" id="z"> document.querySelectorAll('input').forEach(input=>console.log("Name:", input.id, "Value:", input.value)); I tried that way, but x,y and z are not declared
@Pawel What do you mean by not declared? document.querySelectorAll just gets a collection of all the input elements which you can loop through.
@Pawel I have also updated my answer to provide some additional guidance.
I would love to collect all 4 inputs and take action, after show result. Trying to understand how it works. Thank you for help
@Pawel No problem. Do you still need help with anything?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.