Convert Form Data To JSON – FormsJS

Category: Form , Javascript | August 13, 2020
Author:e3ndr
Views Total:2,534 views
Official Page:Go to website
Last Update:August 13, 2020
License:MIT

Preview:

Convert Form Data To JSON – FormsJS

Description:

FormsJS is a simple-to-use JavaScript library that coverts form field values to JSON in real-time.

How to use it:

1. Add the CSS class ‘data’ to form fields as follows:

<div id="form">
  <h1 class="title">Form</h1>
  <label class="label">
  Username
  <input class="input data" name="username" type="text" value="formsjs_" />
  </label>
  <label class="label">
  Send me promotional emails
  <br />
  <input class="checkbox data" name="allow_promotional_emails" type="checkbox" />
  <br />
  </label>
  <label class="label">
    Gender
    <br />
    <div class="select control">
      <select class="data" name="gender">
        <option selected value="unknown">Prefer not to say</option>
        <option value="other">Other</option>
        <option value="female">Female</option>
        <option value="male">Male</option>
      </select>
    </div>
  </label>
  <label class="label">
    Where do you live?
    <br />
    <div class="select control">
      <select class="data" name="zipcode">
        <option value="">Elsewhere</option>
        <option value="94016">San Francisco</option>
        <option value="94088">San Jose</option>
      </select>
    </div>
  </label>
  <div class="control">
    <label class="label">
    Account Type
    </label>
    <label class="radio">
    <input class="data" checked type="radio" name="account_type" value="free" />
    Free Account
    </label>
    <label class="radio">
    <input class="data" type="radio" name="account_type" value="premium" />
    Premium Account
    </label>
  </div>
</div>

2. Convert field values into a JSON object:

function submit() {
  let username = document.querySelector("[name=username]");
  let result = FORMSJS.readForm("#form");
  // Make the username box turn red if its length is less than 8
  if (username.value.length < 8) {
      username.classList.remove("is-success");
      username.classList.add("is-danger");
  } else {
      username.classList.remove("is-danger");
      username.classList.add("is-success");
  }
  console.log(result);
}
Array.from(document.querySelector("#form").getElementsByClassName("data")).forEach((element) => {
  element.addEventListener("change", submit);
});

3. The JSON object should be like these:

{
  "username": "formsjs_",
  "allow_promotional_emails": false,
  "gender": "unknown",
  "zipcode": null,
  "account_type": "free"
}

You Might Be Interested In:


Leave a Reply