How to Prefill a Form Using JavaScript?

Estimated read time 2 min read

To prefill a form using JavaScript, you need to access the form elements, such as text fields and checkboxes, and set their values to the desired prefilled data. Here’s an example of how to prefill a simple form with JavaScript:

// get form elements
var firstName = document.getElementById("first-name");
var lastName = document.getElementById("last-name");
var email = document.getElementById("email");

// set form values
firstName.value = "John";
lastName.value = "Doe";
email.value = "john.doe@example.com";

In the above code, we use the document.getElementById method to access the form elements by their ID, and then set their value property to the desired prefilled data.

You can also use JavaScript to prefill checkboxes and select boxes. Here’s an example:

// get form elements
var gender = document.getElementById("gender");
var subscribe = document.getElementById("subscribe");

// set form values
gender.value = "Male";
subscribe.checked = true;

In this example, we access the gender select box and set its value property to the desired option, and we access the subscribe checkbox and set its checked property to true.

You can also use JavaScript to prefill a form dynamically, based on data from a server or other source. For example, you can use the fetch API to retrieve data from a server, and then use that data to prefill the form. Here’s an example:

fetch("data.json")
  .then(response => response.json())
  .then(data => {
    // get form elements
    var firstName = document.getElementById("first-name");
    var lastName = document.getElementById("last-name");
    var email = document.getElementById("email");

    // set form values
    firstName.value = data.firstName;
    lastName.value = data.lastName;
    email.value = data.email;
  });

In this example, we use the fetch API to retrieve data from a server in JSON format, and then use that data to prefill the form.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply