Populate Form fields From JSON – populatejs

Category: Form , Javascript | September 23, 2018
Author:dastagirkhan
Views Total:3,071 views
Official Page:Go to website
Last Update:September 23, 2018
License:MIT

Preview:

Populate Form fields From JSON – populatejs

Description:

populatejs is a pure JavaScript plugin for dynamic form creation that populates existing form fields from a JSON object.

How to use it:

Make sure your form fields have unique name values.

<form action="">
  <fieldset>
      <legend>PopulateJS</legend>
      <label class="form-label" for="last_name">Last name</label>&nbsp;
      <input type="text" name="last_name" id="last_name">
      <br>
      <legend>Feature</legend>
      <label for="horns">Horns</label>
      <input type="checkbox" id="horns" name="feature" value="horns" />
      <br>
      <label for="claws">Claws</label>
      <input type="checkbox" id="claws" name="feature" value="claws" />
      <br>
      <label for="scales">Scales</label>
      <input type="checkbox" id="scales" name="feature" value="scales" />
      <br>
      <legend>Sex</legend>
      <label for="male">Male</label>
      <input type="radio" id="male" name="sex" value="male" />
      <label for="female">Female</label>
      <input type="radio" id="female" name="sex" value="female" />
      <br>
      <legend>Choose a pet:</legend>
      <br>
      <select id="pet-select" name="pet-select">
          <option value="">--Please choose an option--</option>
          <option value="dog">Dog</option>
          <option value="cat">Cat</option>
          <option value="parrot">Parrot</option>
          <option value="spider">Spider</option>
          <option value="goldfish">Goldfish</option>
      </select>
      <br>
      <br>
      <legend>Choose multiple pets:</legend>
      <br>
      <select id="pet-select-multiple" name="pet-select-multiple" multiple size="10">
          <option value="none">-- Please choose one or more --</option>
          <optgroup label="4-legged pets">
              <option value="dog">Dog</option>
              <option value="cat">Cat</option>
          </optgroup>
          <optgroup label="Flying pets">
              <option value="parrot">Parrot</option>
              <option value="macaw">Macaw</option>
              <option value="albatross">Albatross</option>
          </optgroup>
      </select>
  </fieldset>
</form>

Download and insert the JavaScript file populatejs.min.js into the page.

<script src="populatejs.min.js"></script>

Initialize the populatejs and define a JSON object containing key-value pairs where keys are the names of the form element .

(function () {
  populatejs({
      'last_name': 'cssscript',
      'feature': 'claws,scales',
      'sex': 'male',
      'pet-select': 'cat',
      'pet-select-multiple': 'dog,macaw'
  });
})();

You Might Be Interested In:


Leave a Reply