javascript - Select all checkbox of table on click of the another table checkbox using react - Stack Overflow

I have checkboxes for each td in a table. Now, I have another table which has one checkbox. On checking

I have checkboxes for each td in a table. Now, I have another table which has one checkbox. On checking this, I want to select all other checkboxes of first table.

Here is the code,

<tr key={key}>
    <td align="center"> <input type="checkbox" name="myTextEditBox" value="checked" /></td>
    <td>{item.technology}</td>
</tr>

for second table I did,

handleCheckBox = () => {
    console.log("callling the handle change");
    this.setState({
      isCheckd: !this.state.isCheckd
    })
}

constructure(props) {
    this.state = { isCheckd: false }
    <td className="text-right mr-1"><input type="checkbox" checked={this.state.isCheckd} onChange={this.handleCheckBox}  /></td>
}

Now, In this click handler works. But, now how do I select all other checkboxes of another table, without using jquery.

Can any one help me with this ?

Tried solution -

state = { dynamicProp: {},  isCheckd: false,}

    handleCheckBox = () => {
        this.setState({
          isCheckd: !this.state.isCheckd
        }, () => {
          this.props.jobs.forEach((item) =>
            this.setState(prevState => ({
              dynamicProp: {
                ...prevState.dynamicProp,
                [item.jdName]: prevState.isCheckd
              }
            })
            ))
        });
      }

      handleTableCheckboxChange = (e) => {
        const target = e.target.name;
        const checked = e.target.checked;
        this.setState(prevState => ({
          dynamicProp: {
            ...prevState.dynamicProp,
            [target]: checked
          }
        }), () => {
          const result = this.allTrue(this.state.dynamicProp);
          this.setState({
            isCheckd: result ? false : true
          })
        })
      }



 allTrue(obj) {
    for (var o in obj)
      if (!obj[o]) return true;
    return false;
  }

and then passing all the props to the child element. Now, the problem I am facing now is in the handleTableCheckboxChange method where I am not getting the way you used filter to get the unchecked element. and then the select all check will get changed.

I have checkboxes for each td in a table. Now, I have another table which has one checkbox. On checking this, I want to select all other checkboxes of first table.

Here is the code,

<tr key={key}>
    <td align="center"> <input type="checkbox" name="myTextEditBox" value="checked" /></td>
    <td>{item.technology}</td>
</tr>

for second table I did,

handleCheckBox = () => {
    console.log("callling the handle change");
    this.setState({
      isCheckd: !this.state.isCheckd
    })
}

constructure(props) {
    this.state = { isCheckd: false }
    <td className="text-right mr-1"><input type="checkbox" checked={this.state.isCheckd} onChange={this.handleCheckBox}  /></td>
}

Now, In this click handler works. But, now how do I select all other checkboxes of another table, without using jquery.

Can any one help me with this ?

Tried solution -

state = { dynamicProp: {},  isCheckd: false,}

    handleCheckBox = () => {
        this.setState({
          isCheckd: !this.state.isCheckd
        }, () => {
          this.props.jobs.forEach((item) =>
            this.setState(prevState => ({
              dynamicProp: {
                ...prevState.dynamicProp,
                [item.jdName]: prevState.isCheckd
              }
            })
            ))
        });
      }

      handleTableCheckboxChange = (e) => {
        const target = e.target.name;
        const checked = e.target.checked;
        this.setState(prevState => ({
          dynamicProp: {
            ...prevState.dynamicProp,
            [target]: checked
          }
        }), () => {
          const result = this.allTrue(this.state.dynamicProp);
          this.setState({
            isCheckd: result ? false : true
          })
        })
      }



 allTrue(obj) {
    for (var o in obj)
      if (!obj[o]) return true;
    return false;
  }

and then passing all the props to the child element. Now, the problem I am facing now is in the handleTableCheckboxChange method where I am not getting the way you used filter to get the unchecked element. and then the select all check will get changed.

Share Improve this question edited Mar 26, 2019 at 6:20 ganesh kaspate asked Mar 20, 2019 at 6:00 ganesh kaspateganesh kaspate 2,69512 gold badges52 silver badges105 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2

I did not understand your code well so I understand it from what you have written. And then I have created a working example for you. Hope it can help you!

UPDATED CODE

const Table=(props)=>(
   <table>
   {
      props.items.map((item, i) => (
        <tr key={i}>
           <td>
             <input type="checkbox"  checked={props.parentState[item.name]}  name={item.name} onChange={props.handleChange} />
           </td>
           <td>{item.value}</td>
        </tr>
      ))
   }
   </table>
);

class App extends React.Component {
    items = [
        {
            value: 'EN',
            name: 'field1'
        },
        {
            value: 'IT',
            name: 'field2',
        }
    ];

    state = {
        checkAll: false,
    };

    render() {
        return (
            <div>
                Check All
                <input type="checkbox" onChange={this.handleCheckAll} checked={this.state.checkAll}/>
                <Table
                   handleChange={this.handleChange}
                   items={this.items}
                   parentState={this.state}
                />
            </div>
        );
    }

    handleCheckAll = () => {
        this.setState({
            checkAll: !this.state.checkAll
        }, () => {
            this.items.forEach((item) => this.setState({ [item.name]: this.state.checkAll}))
      });
    }

    handleChange = (e) => {
        this.setState({
            [e.target.name]: e.target.checked
        }, () => {
             const uncheckedItems = this.items.filter((item) => !this.state[item.name])

             this.setState({
                  checkAll: uncheckedItems.length === 0?true:false
             });
            
        });
    }
}

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>

Here's a sample code. Obviously i haven't covered all the fail cases. Still you will get an idea about how that can be done.

import React from 'react';

export default class CheckboxIndex extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            isChecked : false,
            allTDS : [
                {name:"name 1",value:false},
                {name:"name 2",value:false},
                {name:"name 3",value:false},
                {name:"name 4",value:false},
                {name:"name 5",value:false},
                {name:"name 6",value:false},
                {name:"name 7",value:false}
            ]
        }
    }

    handleCheckBox = () => {
        this.setState({isChecked: !this.state.isChecked});
        let tempTDS = this.state.allTDS;
        for (let i =0; i < tempTDS.length; i++){
            tempTDS[i].value = !this.state.isChecked;
        }
        this.setState({allTDS : tempTDS});
    };

    render(){
        let listOfTR;
        if(this.state.allTDS.length){
            listOfTR = this.state.allTDS.map((item,index)=>{
                return(
                    <tr key={item.name}>
                        <td>
                            <label htmlFor={item.name}>
                            <input id={item.name} checked={item.value} type="checkbox"
                                   onChange={()=>{
                                       let tempObj = this.state.allTDS;
                                       tempObj[index].value = !tempObj[index].value;
                                       this.setState({allTDS:tempObj});
                                   }}/>{item.name}
                            </label>
                        </td>
                    </tr>
                )
            })
        }
        return(
                <div>
                    <label htmlFor="allTDS">
                        <input type="checkbox" id="allTDS" name="all" checked={this.state.isChecked}
                               onChange={this.handleCheckBox}/> All
                    </label>

                    <table>
                        <tbody>
                        {listOfTR}
                        </tbody>
                    </table>
                </div>
        )
    }
}
class CheckboxTest extends React.Component {
  constructor() {
    super();
    this.state = {
      selectAll: false,
      data1: false,
      data2: false
    };
    this.selectAll = this.selectAll.bind(this);
    this.selectField = this.selectField.bind(this);
  }
  selectAll() {
    this.setState({
      data1: !this.state.selectAll,
      data2: !this.state.selectAll,
      selectAll: !this.state.selectAll
    });
  }
  selectField(event) {
    if (event.target.value === "data1")
      this.setState({ data1: !this.state.data1 });
    else this.setState({ data2: !this.state.data2 });
  }
  render() {
    return (
      <div className="App">
        <table>
          <tbody>
            <tr>
              <td align="center">
                <input
                  checked={this.state.data1}
                  onChange={this.selectField}
                  type="checkbox"
                  name="myTextEditBox1"
                  value="data1"
                />
              </td>
              <td>data 1</td>
            </tr>
            <tr>
              <td align="center">
                <input
                  checked={this.state.data2}
                  onChange={this.selectField}
                  type="checkbox"
                  name="myTextEditBox2"
                  value="data2"
                />
              </td>
              <td>data 2</td>
            </tr>
          </tbody>
        </table>
        <table>
          <tbody>
            <tr>
              <td align="center">
                <input
                  onChange={this.selectAll}
                  type="checkbox"
                  name="myTextEditBox1"
                  value="all"
                />
              </td>
              <td>Click all</td>
            </tr>
          </tbody>
        </table>
      </div>
    );
  }
}

You can use the state for implementing this. Maintain state for each checkbox field and when the checkbox is changed trigger a method to set the state according to your conditions

 this.setState({
      isCheckd: !this.state.isCheckd
    })

In this case, the isCheckd value in state corresponds to one checkbox. To select all other checkboxes of another table you have to update the values set in setState to all the values that correspond to all the boxes you want checked.

So if you have another 3 checkboxes who's values correspond to isCheckd1, isCheckd2, and isCheckd3 in state then your handler would be:

this.setState({
          isCheckd1: true,
          isCheckd2: true,
          isCheckd3: true
        })

Try this approach. you can select both the individual and check all checkbox.

    class App extends React.Component {
        items = ['EN', 'IT', 'FR', 'GR', 'RU'];
        state = {
          checkAll: false,
          items : [
           {'label': 'EN', 'checked': false},
           {'label': 'IN', 'checked': false}, 
           {'label': 'FR', 'checked': false},   
          ]
        };

        render() {
            return (
              <div>
                Check All
                <input type="checkbox" onChange={this.handleCheckAll} />
                <table>
                    {
                        this.state.items.map((item, i) => (
                            <tr key={i}>
                                <td>
                                  <input type="checkbox" checked={item.checked} />
                                </td>
                                <td>{item.label}</td>
                            </tr>
                        ))
                    }
                </table>
              </div>
            );
        }

        handleCheckAll = () => {
          let checkAll = !this.state.checkAll;
          let items = this.state.items;
          items.map((item, i) => {
            item.checked = checkAll;
          });
          this.setState({
            checkAll, 
            items
          });
        }
    }

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

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

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

关注微信