Why radiobutton isn't checked?

123 views Asked by At

I have

<input type='radio' name='is_active' value='true' checked={this.props.is_active==true ? true : false}/> Active
<input type='radio' name='is_active' value='false' checked={this.props.is_active==false ? true : false}/> Passive
...
<button>Save</button>

When I reload page radiobutton is checked as it should, but when I try to check another I can't select anything (dot in radiobutton disappears) But when I click save it saves right !!! (value of the last radiobutton pressed). I can't understand.. Maybe someone knows what's wrong ?

2

There are 2 answers

0
Gayane On BEST ANSWER

you should have state for rendering your html with new values. set your initial state like this (if you're using es6):

constructor (props) {
 super(props)
 this.state = {
  is_active: this.props.is_active
 }
}

also you will need a function to call on button's click, which will change the state:

setCheckedValue (val) {
 this.setState({is_active: val})
}

and finally your html will look like this:

<input type='radio' name='is_active' value='true' checked={this.state.is_active==true ? true : false} onClick={this.setCheckedValue.bind(this, 'true')}/> Active
<input type='radio' name='is_active' value='false' checked={this.state.is_active==false ? true : false} onClick={this.setCheckedValue.bind(this, 'false')}/> Passive
0
puritys On

You have to add a onClick event to change the value of is_active.

<label><input type='radio' name='is_active' value='true' checked={this.props.is_active==true ? true : false} onClick={this.props.is_active=true} /> Active</label>
<label><input type='radio' name='is_active' value='false' checked={this.props.is_active==false ? true : false} onClick={this.props.is_active=false} /> Passive</label>                                                    
<button>Save</button>