I want to change value of my checkboxes from true to false
var x = document.getElementsByClassName("checkbox")
for(let i=0; i<=x.length; i++) {
x[i].checked = false;
}
but when I try to do this I get an error: Cannot set properties of undefined (setting 'checked') because x is HTMLCollection and x[i] returns only
<input type="checkbox" class="checkbox">
so no 'checked' property.
How can I handle this?
Please either change the <= to < in the for loop
for(let i=0; i<x.length; i++) {}
Or make it to loop till length - 1
for(let i=0; i<=x.length - 1; i++) {}
The issue with how you're doing it is that you're not making use of the states in React.
This is how I would do it.
Set initial state of the checkboxes:
constructor(props) {
super(props);
this.state = {checked : false};
}
then pass the state into the checked property of the input:
<input type="checkbox" checked={this.state.checked} onChange={(e) => this.handleChange(e)} />
In the handleChange function update the state of the checkbox:
handleChange = (e) => {
this.setState({ checked: e.target.checked })
}
This should update all the checkboxes that have checked={this.state.checked}
Try this:
<input type="checkbox" checked={this.state.chkbox} onChange={this.handleChangeChk} />
Or you can check this question here briefly explained: