mercredi 22 avril 2020

Use checkbox to find the sum of selected values - ReactJS

I am trying to calculate the total value ({account.fee})of the selected checked boxes and display it. So, each time I select a checkbox, it gets summed up to the total value.

state={
    checked: false,
    total: 0
  }

  totalValue=(e, input)=> {
    console.log(total);
    const { checked, type } = e.target;
    let { total } = this.state;
    if (type === "checkbox" && checked === true) {
    this.props.account.each((account) => {
      return (
        total += account.fee
      )
    }

    this.setState({
      total
    });
  }

render(){
    // console.log(this.state);
    // console.log(this.props.debt);
    return(
<div>
        <table>
        <thead>
        <tr>
          <th className="select_all">
            <input type="checkbox" name="check" id="parent"
                totalValue={()=>this.totalValue}
              />

          </th>
          <th>FirstName</th>
          <th>LastName</th>
          <th>Fee</th>
        </tr>
        </thead>
          <tbody>
          {
            this.props.account.map((account, i) => {
              return(
                  <tr key={i}>
                      <td className="select">
                        <input type="checkbox" name="check1" id="child_check"
                          onChange={this.onSelectChange.bind(this)}
                          totalValue={()=>this.totalValue}
                          } />
                      </td>
                      <td>{account.firstName}</td>
                      <td>{account.lastName}</td>
                      <td >{account.fee}</td>
                    </tr>
                  )
                })
              }
          </tbody>
        </table>

)}
<p>Total: {this.state.total}</p>
</div>
    );
  }



Aucun commentaire:

Enregistrer un commentaire