Ishimdar Ahamad
Ishimdar Ahamad

Reputation: 202

How to change input value after onSubmit event not onChange?

I am not able to change input value onSubmit, can You please help me.

*https://jsfiddle.net/ishimdar/jx774dm3/*

Upvotes: 0

Views: 36

Answers (1)

Mirko Acimovic
Mirko Acimovic

Reputation: 506

You can use reference to an input field and change its value. In this example I marked first input but you can mark others same way. Refs will hold all your refernces to elements so you can access them by ref name.

class TodoApp extends React.Component {
   constructor(props){
            super(props);
            this.state = {
                width: '',
                height: '',
                background: '',
            };
            this.handleSubmit = this.handleSubmit.bind(this);
            this.handleChange = this.handleChange.bind(this);
        }

        handleChange(event){
            this.setState({
                [event.target.name]: event.target.value
            });
        }

        handleSubmit(event){

            this.refs.a.value = "New value"; // change value of input field
            event.preventDefault();

        }

        render(){
            var changeDiv = (
                    <div style={this.state}>
                        width: {this.state.width}
                        height: {this.state.height}
                        bg: {this.state.background}
                    </div>
            );
            return(
                    <div className="parentDiv">
                        <form onSubmit={this.handleSubmit}>
                            <div>
                                Set height<br/>
                                <input type="text" ref='a' name="width" value={this.state.width} onChange={this.handleChange} />
                            </div>
                            <div>
                                Set width<br/>
                                <input type="text" name="height" value={this.state.height} onChange={this.handleChange} />
                            </div>
                            <div>
                                Set background<br/>
                                <input type="text" name="background" value={this.state.background} onChange={this.handleChange} />
                            </div>
                            <div>
                                <input type="submit" value="Change div" />
                            </div>
                        </form>
                        {changeDiv}
                    </div>
            );
        }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

Upvotes: 1

Related Questions