Hi, I’m a mouse

Here is a simple login form:

  <form 
      action="http://localhost:3000/user/login" 
      method="post" 
      id="login-form" 
      enctype="application/x-www-form-urlencoded"
  >
    <label for="username">User name:</label>
    <input type="text" placeholder="Please Input your username" name="username" id="username">
        <br>
    <label for="password">Password:</label>
    <input type="password" placeholder="Please Input your password" name="password" id="password">
        <br>
    <button type="submit">submit</button>
  </form>
Copy the code

Without javascript to process it, when we click the submit button, the form is sent to the action with the form elements name and value as key-value pairs and the element form’s Method method.

However, in most development frameworks, we use javascript to encapsulate forms. In this article, I want to share some tips on how to handle forms.

Get form data using Javascript

1. Obtain the form

  • Through document.getelementby **, querySelector, etc.

  • throughdocument.forms[id/index]Get the specified form

2. Block form default events

To prevent the form from jumping and sending data by default, we do this by listening for the Form element’s Submit event,

There are two ways to do this:

  • return false
  • througheventObject, sete.preventDefault

E.preventdefault () + E.topPropagation ()

let form = document.getElementById("login-form");
form.onsubmit = (event) = > {
  return false;
}
Copy the code

Now clicking the Submit button will no longer automatically send data and jump.

3. Process form data

So now let’s start working with form data:

  • The corresponding form control can be obtained via the name property and the ID property:

  • Obtain from form index:

  • Get data in bulk through FormData:

    It is important to note that formData is a snapshot of data, which is equivalent to generating objects from name and value.

    When the data changes again, formData must be recreated.

    Second, formData cannot retrieve content directly and must retrieve it through entries() related loops or get.

    Ps: We can simplify this by adding a formData attribute to the HTMLFormElement prototype:

    In the same way, we can also encapsulate data.

  • Encapsulating JSON forms:

    Object.defineProperty(HTMLFormElement.prototype, 'jsonData', {
       get() {
           const jsonData = {};
           const formData = new FormData(this);
           formData.append("1"."2");
           formData.append("1"."3");
           formData.forEach((value, key) = > {
               if(! jsonData[key]) { jsonData[key] = formData.getAll(key);if (jsonData[key].length < 1) jsonData[key] = "";
                   else if (jsonData[key].length === 1) jsonData[key] = jsonData[key][0]; }});returnjsonData; }})Copy the code

4. Send form data

  • Form.submit () sends data normally and jumps

  • Use Ajax in onSubmit to send the form object encapsulated in 3

    let xhr = new XMLHttpRequest();
    xhr.open("POST".'/server'.true);
    xhr.setRequestHeader("Content-type"."application/x-www-form-urlencoded");
    xhr.send(formata);
    Copy the code

    Attention needed! FormData is sent as multipart/form-data by default, even if we set XHR to Application/X-www-form-urlencoded, the server will receive the following result:

    Therefore, we usually borrow the third point, converting the form to a JSON object or a URL object and sending it.

If you’re interested in how the back end handles formData, check out this article: Koa2 uses koa-bodyparser + multer to parse formData and other data types;

React handles form data

Controlled Components (recommended)

Refers to a bidirectionally bound form control that associates the form control value with the component state:

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('Submitted by name:' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>Name:<input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>); }}Copy the code

More controlled Components

Uncontrolled component

The form component is maintained by the native DOM component, which fetches values from the native form control by creating a REF:

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.input = React.createRef();
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.input.current.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" ref={this.input} />
        </label>
        <input type="submit" value="Submit" />
      </form>); }}Copy the code

conclusion

Thank you for watching, like and follow is my biggest support.

You are also welcome to supplement and discuss the content of the article!

How does XboxYan get form data elegantly