admin管理员组文章数量:1421046
I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values in a div tag.
I am trying to run this event whenever a user types in any of the inputs
The problem is I am sure React has a proper way to do this!
This is my feeble attempt (please go easy - I am new to coding :)
HTML
<input type="number" id="p1" name="p1" onChange={this.handleTotal} />
<input type="number" id="p2" name="p2" onChange={this.handleTotal} />
<input type="number" id="p3" name="p3" onChange={this.handleTotal} />
<input type="number" id="p4" name="p4" onChange={this.handleTotal} />
<input type="number" id="p5" name="p5" onChange={this.handleTotal} />
<input type="number" id="p6" name="p6" onChange={this.handleTotal} />
<div id=total></div>
JS
handleTotal = e => {
// Grab all inputs that start with ID 'p'
let inputs = document.querySelectorAll('[id^="p"]');
// Trying to loop through the values and get the sum of all inputs
for (var i = 0; i < inputs.length; i++) {
let totalVal = inputs[i].value
console.log(totalVal);
}
//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}
I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values in a div tag.
I am trying to run this event whenever a user types in any of the inputs
The problem is I am sure React has a proper way to do this!
This is my feeble attempt (please go easy - I am new to coding :)
HTML
<input type="number" id="p1" name="p1" onChange={this.handleTotal} />
<input type="number" id="p2" name="p2" onChange={this.handleTotal} />
<input type="number" id="p3" name="p3" onChange={this.handleTotal} />
<input type="number" id="p4" name="p4" onChange={this.handleTotal} />
<input type="number" id="p5" name="p5" onChange={this.handleTotal} />
<input type="number" id="p6" name="p6" onChange={this.handleTotal} />
<div id=total></div>
JS
handleTotal = e => {
// Grab all inputs that start with ID 'p'
let inputs = document.querySelectorAll('[id^="p"]');
// Trying to loop through the values and get the sum of all inputs
for (var i = 0; i < inputs.length; i++) {
let totalVal = inputs[i].value
console.log(totalVal);
}
//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}
Share
Improve this question
asked Mar 4, 2020 at 16:43
js-learnerjs-learner
5172 gold badges11 silver badges28 bronze badges
3 Answers
Reset to default 2At the moment you are not utilizing any of the React's data binding.
Best to use React's state to hold the values of the total
and all the p
inputs.
I've also used the .reduce method in order to calculate the total for each of the input fields' values. But you can achieve the same thing with a for
loop.
JSFiddle: Alternative "calculateTotal" function with for loop
More information on Input handling in React
class App extends React.Component {
constructor() {
super();
this.state = {
total: 0,
numbers: {
p1: 1,
p2: 0,
p3: 4,
p4: 0,
p5: 0,
p6: 0
}
};
}
ponentDidMount() {
// Calculates the total after ponent is mounted
this.setState({ total: this.calculateTotal(this.state.numbers) });
}
calculateTotal = (numbers) => {
return Object.entries(numbers).reduce((finalValue, [key, value]) => {
if (value === "") {
// if entered value is empty string "", omits it
return finalValue;
}
return finalValue + value;
}, 0);
}
handleTotal = (e) => {
const { value, name } = e.target; // gets the name and value from input field
const parsedValue = value === "" ? "" : parseFloat(value); // parses the value as a number or if empty treats it as empty string ""
this.setState((prevState) => {
// creates new immutable numbers object, using previous number values and the currently changed input value
const updatedNumbers = {
...prevState.numbers,
[name]: parsedValue
// https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#Computed_property_names
};
// calculates the new total from updated numbers:
const newTotal = this.calculateTotal(updatedNumbers);
return {
numbers: updatedNumbers,
total: newTotal
}
})
}
render() {
return (
<div>
<input type="number" name="p1" onChange={this.handleTotal} value={this.state.numbers.p1} />
<input type="number" name="p2" onChange={this.handleTotal} value={this.state.numbers.p2}/>
<input type="number" name="p3" onChange={this.handleTotal} value={this.state.numbers.p3}/>
<input type="number" name="p4" onChange={this.handleTotal} value={this.state.numbers.p4}/>
<input type="number" name="p5" onChange={this.handleTotal} value={this.state.numbers.p5}/>
<input type="number" name="p6" onChange={this.handleTotal} value={this.state.numbers.p6}/>
<div id="total">{this.state.total}</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare./ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
const handleFormSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
let total = 0;
for (let [key, value] of formData.entries()) {
total += value * 1;
}
document.querySelector('#total').textContent = total;
};
document.addEventListener('DOMContentLoaded', () => {
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit, false);
});
<form>
<input type="number" id="p1" name="p1" />
<input type="number" id="p2" name="p2" />
<input type="number" id="p3" name="p3" />
<input type="number" id="p4" name="p4" />
<input type="number" id="p5" name="p5" />
<input type="number" id="p6" name="p6" />
<button type="submit">submit</button>
</form>
<span>total</span>
<div id=total></div>
You just re-assign variable in every iteration of a loop. Change to smth like this:
handleTotal = e => {
// Grab all inputs that start with ID 'p'
let inputs = document.querySelectorAll('[id^="p"]');
// Trying to loop through the values and get the sum of all inputs
let totalVal=0
for (var i = 0; i < inputs.length; i++) {
totalVal += inputs[i].value
console.log(totalVal);
}
//Trying to grab total values of all inputs and put in element
document.getElementById('total').innerHTML = totalVal;
}
+=
operator just adds value of next element to total variable. it is equal to totalVal = totalVal + inputs[i].value
本文标签: javascriptReactLoop inputs and get sum valueStack Overflow
版权声明:本文标题:javascript - React - Loop inputs and get sum value - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745327971a2653680.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论