Populate form fields from different sources with JavaScript

In this article, you can find examples of how to use JavaScript to populate fields from different sources, such as URL parameters or browser’s local storage.

Populate fields from a URL parameter

If you want to share a form with some fields pre-filled, then the URL parameters are the best option to do so. You need to add the parameters to the URL, and then parse them on the form, populating the fields:

//use URL with parameters, for example:
    var queryString = window.location.search;
    var urlParams = new URLSearchParams(queryString);
    fd.field('Text1').value = urlParams.get('param1');
    fd.field('Text2').value = urlParams.get('param2');

Populate fields from browser’s local storage

If you want to store some data in the browser’s cache, you can use local storage for that. For example, you can save some values while the user is working with one form, then retrieve them when the user opens up another form, like this:

//store values in local storage like this:
localStorage.setItem('value1', 'Hello, world!');
localStorage.setItem('value2', fd.field('Text0').value);

//retrieve values from local storage
    var value1 = localStorage.getItem('value1');
    var value2 = localStorage.getItem('value2');
        fd.field('Text1').value = value1;
        fd.field('Text2').value = value2;

You can also store all of the form’s data and populate form with same values when it’s opened again, like this:

//save form data before save
    localStorage.setItem('form-data', JSON.stringify(fd.data()));

//populate form data when form opens
    var data = JSON.parse(localStorage.getItem('form-data'));

Populate fields from external API

When the form opens, you can make requests to an external API and retrieve values from the API. You’ll need to make sure that you have the key if it’s needed and that you follow the instructions from the API developers, but here’s an example of how it can be done with ipapi.co, an API that will help us determine person’s location and IP:

//make a request when the form opens
    $.getJSON('https://ipapi.co/json/', function (response) {
        fd.field('Location').value = response.city + ', ' + response.region_code + ', ' + response.country_name;
        fd.field('IP').value = response.ip;