javascript - React - Loop inputs and get sum value - Stack Overflow

I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values

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
Add a ment  | 

3 Answers 3

Reset to default 2

At 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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745327971a4622746.html

相关推荐

  • javascript - React - Loop inputs and get sum value - Stack Overflow

    I am attempting to in React JS to get the sum of a group inputs, and put the sum of their total values

    4小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信