I am using React, and would like to retrieve POST params from a form (see below):
<form ref='form' className="form">
<input type="text" className="signup-input" />
<input type="text" className="signup-input" />
<button className="btn btn-primary" onClick={this._onSubmitClick}>Submit</button>
</form>
In the _onSubmitClick
callback, I would like to achieve the same results as calling $(".form").serialize()
but without using JQuery.
in addition to the answer i think somebody will love this ;)
export default class LoginView extends React.Component {
handleSubmit(evt) {
const formData = Array.from(evt.target.elements)
.filter(el => el.name)
.reduce((a, b) => ({...a, [b.name]: b.value}), {});
console.log(formData);
evt.preventDefault();
return false;
}
render() {
return (<form onSubmit={this.handleSubmit}>...</form>)
}
}
You can place ref
on each input
:
<form ref='form' className="form">
<input type="text" ref="firstName" className="signup-input" />
<input type="text" ref="lastName" className="signup-input" />
<button className="btn btn-primary" onClick={this._onSubmitClick}>Submit</button>
</form>
And then to use React.findDOMNode
to access them in _onSubmitClick
:
_onSubmitClick: function() {
var firstName = React.findDOMNode(this.refs.firstName).getValue();
var lastName = React.findDOMNode(this.refs.lastName).getValue();
// ...
}
var elements = this.refs.form.getDOMNode().elements;
gives you an object containing each of the input
nodes, which you could then iterate through.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With