Reputation: 43
im trying to find a way to trigger the submit event manually, just like a button with type="submit" would. I found a way to do that, from another post here, but unfortunately it doesn't check if the required inputs contain values and submits the form even when no text was typed into the input:
https://codesandbox.io/s/q92855nz3w
or
import React from "react";
import { render } from "react-dom";
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({ value: event.target.value });
}
handleSubmit(event) {
alert("A name was submitted: " + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div onClick={this.handleSubmit}>SOME DIV</div>
<label>
Name:
<input
type="text"
value={this.state.value}
onChange={this.handleChange}
required
/>
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
render(<NameForm />, document.getElementById("root"));
Thanks for any help in advance!
Upvotes: 1
Views: 1266
Reputation: 43
Found a solution to my question:
var form = document.getElementById("form");
form.reportValidity();
Upvotes: 1