1

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.

5 Answers 5

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.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="root"></div>

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

12 Comments

Yes, I can do this way as well, I can select all on the basis of that prop only. But then that td can also be individually select, in your solution we can not select it individually
you can take an onChange for those td and manage those state based on the checkbox name property. in onChangeHandler you can update the state for each checkbox dynamically. this.setState({[e.target.name]:checkedValue}); and then you can check if all fields value is checked checck all checkbox also should get checked
So, Here we are already using checked={this.state.checkAll} this state prop then How do we use another state prop with the checked only
give unique name property to each checkbox and then this.setState({[e.target.name]:e.target.checked});
let me make it for you.
|
1

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>
        )
    }
}

Comments

0
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

Comments

0
 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
        })

3 Comments

Actually, another table is rendering using the map
it is like, user can check that checkboxes individually or else user can select all using the select all
Sure, so the select all will need its own handler function and that function will need to update the state of all of the value that corresponds to the checkboxes you want updated.
0

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
          });
        }
    }

Comments

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.