I have multiple text input fields and a single checkbox. Whenever I check the checkbox, I want to clear one of my text input fields. I looked at various answers for this, however, none of them worked.
Here is my code:
import React, { Component } from 'react';
class Form extends Component {
state = {}
constructor(props) {
super(props);
this.state = {
text1: "",
text2: ""
};
this.handleChange = this.handleChange.bind(this);
this.handleClear = this.handleClear.bind(this);
}
handleChange(event) {
let name = event.target.name;
let value = event.target.value;
this.setState({[name]: value});
}
handleClear(event){
let checked = event.target.checked;
if(checked){
this.setState({"text2": ''}); // did not work
// how to do it???
console.log(this.state)
}
}
render() {
return (
<form>
<input type="text" name="text1" onChange={this.handleChange}/>
<input type="text" name="text2" onChange={this.handleChange}/>
<input type="checkbox" name="clear-text2" onChange={this.handleClear}/>
</form>
);
}
}
export default Form;
In this code, I want the field text2
to get cleared when the checkbox is checked. Kindly help me with this. Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire