I have made 4 radio buttons for 1 question. I have made 2 buttons submit and clear input. When I submit the form after clicking on clear input it does not clear the checked buttons to unchecked how can I do that using reset
function ?
contactform.js:
import React, { Component } from 'react';
class ContactForm extends Component {
constructor(props){
super(props);
this.state = {
age:'',
gender:'',
health:'',
name:'',
email:'',
info:'',
fitness:''
};
}
setAge(checkedValue){
console.log(checkedValue);
this.setState({
age:checkedValue
})
}
setGender(checkedValue){
console.log(checkedValue);
this.setState({
gender:checkedValue
})
}
onChangeTextBoxGender(event){
this.setState({gender: event.target.value})
}
savedata(age, gender, health, name, email, info, fitness){
let newcontent = contentref.push();
newcontent.set({
age:this.state.age,
gender:this.state.gender,
health:this.state.health,
name:this.state.name,
email:this.state.email,
info:this.state.info,
fitness:this.state.fitness
});
}
reset(){
this.setState({
age:'',
gender:''
})
}
render() {
return (
<div>
<div id="center">
<form>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<h3>[Test]Contact us Survey Form</h3>
</div>
</div>
<div id="agegroup" >
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<h4>What is your age group?</h4>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="age" onChange={this.setAge.bind(this,'>=25 yrs')}/> >=25 yrs</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="age" onChange={this.setAge.bind(this,'26-35 yrs')}/> 26-35 yrs</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="age" onChange={this.setAge.bind(this,'36-50 yrs')}/> 36-50 yrs</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="age" onChange={this.setAge.bind(this,'>50 yrs')}/> >50 yrs</label>
</div>
</div>
</div>
</div>
<div id="gender">
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<h4>What is your gender?</h4>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Female')}/> Female</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Male')}/> Male</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Prefer not to say')}/> Prefer not to say</label>
</div>
</div>
</div>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<div className="radio">
<label><input type="radio" name="gender" onChange={this.setGender.bind(this,-1)}/>Other</label>
<input type="text" class="form-inline" id="other1" onChange={this.onChangeTextBoxGender.bind(this)}/>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-success" onClick={this.savedata.bind(this)}>Submit</button>
<button type="button" class="btn btn-danger">Clear input</button>
</form>
</div>
</div>
);
}
}
export default ContactForm;
See screenshots:
Give a checked attribute for you radio button. Change
<label>
<input
type="radio"
name="age"
onChange={this.setAge.bind(this,'>=25 yrs')} />
{' '}
>=25 yrs
</label>
to
<label>
<input
type="radio"
name="age"
checked={(this.state.age == '>=25 yrs')}
onChange={this.setAge.bind(this,'>=25 yrs')}/>
>=25 yrs
</label>
you can control what is selected using the state, below find and example (btw, it is not a good practice generate functions inside the render function because it will cause unnecessary rerenders)
class App extends React.Component {
state = {
selectedValue : ''
}
optionSelected = (e) => {
console.log(e.target.value)
this.setState({
selectedValue : e.target.value
})
}
reset = (e) => {
this.setState({
selectedValue : ''
})
}
render () {
const { selectedValue } = this.state;
return (
<div>
<div>
<input
type="radio"
name="age" value="A"
onChange={this.optionSelected}
checked={selectedValue === 'A'}/> A
</div>
<div>
<input
type="radio"
name="age"
value="B"
onChange={this.optionSelected}
checked={selectedValue === 'B'}/> B
</div>
<div>
<input
type="radio"
name="age"
value="C"
onChange={this.optionSelected}
checked={selectedValue === 'C'}/> C
</div>
<button onClick={this.reset}>reset</button>
</div>
);
}
}
ReactDOM.render(<App/>, document.querySelector('#root'))
You are triggering a onChange handler, updating the state
correctly, but you aren't actually controlling the components with this data. Here's an in-depth guide from react about Uncontrolled Components , and the recommended approach, Controlled Components in Forms.
In your component, you need to manually set the props checked
of each radio input based on the value of this.state
. For example:
render() {
// here you extract the data from the state
const age = this.state.age
const gender = this.state.gender
...
<div className="radio">
<label><input type="radio" name="gender" onChange={this.setGender.bind(this,'Female')} checked={gender === 'Female'}/> Female</label>
</div>
... // and set checked for every input, using the age for the age radio buttons
}
Thus, controlling the components like that, when you call reset
, all inputs'll have the checked
props set to false, and will get unmarked.
In ReactJS:
inputs
can be controlled
via their value
/ checked
props
.
These props
are typically managed via this.state
.
The alternative to controlled components
is uncontrolled components
.
See below for a practical example of how to dynamically construct a radio
form
of controlled components
based on an Array
of Sections
.
// Sections. const sections = [ { id: 'age', name: 'Age', options: [ '20 - 30', '30 - 40', 'Other' ] }, { id: 'gender', name: 'Gender', options: [ 'Male', 'Female', 'Other' ] } ] // Radio Box class RadioBox extends React.Component { // Constructor. constructor(props) { super(props) this.initialState = sections.reduce((state, section) => ({...state, [section.id]: false}), {}) this.state = this.initialState } // Render. render = () => ( <form onSubmit={this.submit}> {sections.map((section, index) => ( <div key={index}> <span>{section.name}</span> <ul> {section.options.map((option, index) => this.option(section.id, option, index))} </ul> <button type="button" onClick={() => this.setState({[section.id]: false})}>Reset {section.name}</button> </div> ))} <button>Submit</button> <button type="button" onClick={() => this.setState({...this.initialState})}>Clear form</button> </form> ) // Submit. submit = (event) => { event.preventDefault() console.log('Data:', this.state) } // Option. option = (id, option, index) => ( <li key={index}> <label>{option}</label> <input type="radio" checked={this.state[id] == option} onChange={(event) => event.target.checked && this.setState({[id]: option})}/> </li> ) } // Mount. ReactDOM.render(<RadioBox/>, document.querySelector('#root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>
在这种情况下,您可以使用简单的 jquery 选择器来选择要清除的值,因此您的重置函数将执行以下操作:
$('input[name="age"]').attr('checked', false);
You can add
checked
property inside your input tag
<input checked={your condition paste here} />
Ex:
<Input type="radio" name="gender" value="male" checked={this.state.gender === "male"} />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.