Onjsdev

Share


How To Fill Form Fields With Url Query Parameters


By onjsdev

Feb 22nd, 2024

If you want to populate form fields with URL parameters when page is loaded, you can easily achieve this using a few lines of javascript code.

Let's say you have a static HTML form with some input fields for name and email variables:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
</head>
<body>
    <h1>Contact Form</h1>
    <form method="post">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        
        <label for="email">Email:</label>
        <input type="email" id="email" name="email">
        
        <input type="submit" value="Submit">
    </form>
</body>
</html>

Now, You can add a few lines of Javascript code to the HTML to read the parameters from the URL and set them as the default values for the form fields.

Here's how you can do it:

window.onload = function() {
  const urlParams = new URLSearchParams(window.location.search);

  // Access form fields by their IDs
  const nameField = document.getElementById("name");
  const emailField = document.getElementById("email");

  // Pre-fill fields based on URL parameters
  if (urlParams.has("name")) {
    nameField.value = urlParams.get("name");
  }
  if (urlParams.has("email")) {
    emailField.value = urlParams.get("email");
  }

  // Adapt for other fields as needed
};

Now, you can test the code using an URL with some parameters like this:

http://127.0.0.1:5500/index.html?name=John&email=john@example.com

When the page loads, the JavaScript will extract these parameters and set them as the default values for the corresponding form fields as shown below:

Fill Form fields through URL parameters with Javascript

Conclusion

That's all. In this article we have showed how to pre-fill the values of form inputs using URL query parameters with HTML and Javascript.

Thank you for reading.