Reputation: 301
I have two radio buttons, one of them is "checked" (according to server response - 0 or 10), and I need to click one of the buttons to send new data to the server (ether value 0 or 10). I have working code, data is sending to the server correctly, all is working. But the problem is - property "checked" is disappearing from both buttons after clicking one of them...
Can some one help me?
this.state = {
status: ""
}
statusHandler(e) {
this.setState({ status: e.target.value });
}
<div className="modal-body">
<div className="form-check form-check-inline">
<input className="form-check-input"
type="radio"
name="inlineRadioOptions"
id="inlineRadio1"
value={0}
checked={this.state.status === 0 ? true : false}
onChange={(e) => this.statusHandler(e)} />
<label className="form-check-label" htmlFor="inlineRadio1">Open</label>
</div>
<div className="form-check form-check-inline">
<input className="form-check-input"
type="radio"
name="inlineRadioOptions"
id="inlineRadio2"
value={10}
checked={this.state.status === 10 ? true : false}
onChange={(e) => this.statusHandler(e)} />
<label className="form-check-label" htmlFor="inlineRadio2">Done</label>
</div>
</div>
Upvotes: 2
Views: 1923
Reputation: 10262
The reason is e.target.value
is giving you 'String' value and you are checking condition with ===
. So you need to convert you value into Number
or you can check condition with ==
.
You can convert you string to number using parseInt
or +e.target.value
.
Please see below code snippet and working stackblitz demo.
class App extends Component {
constructor() {
this.state = {
status: ''
};
}
statusHandler(e) {
this.setState({ status: +e.target.value });
}
render() {
return (
<div className="modal-body">
<div className="form-check form-check-inline">
<input className="form-check-input"
type="radio"
name="inlineRadioOptions"
id="inlineRadio1"
value={0}
checked={this.state.status === 0 ? true : false}
onChange={(e) => this.statusHandler(e)} />
<label className="form-check-label" htmlFor="inlineRadio1">Open</label>
</div>
<div className="form-check form-check-inline">
<input className="form-check-input"
type="radio"
name="inlineRadioOptions"
id="inlineRadio2"
value={10}
checked={this.state.status === 10 ? true : false}
onChange={(e) => this.statusHandler(e)} />
<label className="form-check-label" htmlFor="inlineRadio2">Done</label>
</div>
</div>
);
}
}
Upvotes: 2