Aaron Stackhouse
Aaron Stackhouse

Reputation: 35

Javascript to populate a form field with data extracted from URL Parameters

I am trying to use javascript to extract data from the URL parameter 'utm_source' and add it to a field on a form so that it is stored in my contact database for tracking purposes.

I had previously accomplished this on another site, but when trying to reuse the code it is not working for me.

The page is here (with the included URL parameter to be extracted):

https://members.travisraab.com/country-guitar-clinic-optin-1-1?utm_source=youtube&utm_medium=description

The desired result if for the 'traffic_source' field on my form to be populated with the value from the 'utm_source' URL parameter, in this case 'youtube'.

Here is the code I am using:

<script type="text/javascript">
function addSource() {
  var fieldToChange = document.getElementsByName("form_submission[custom_4]");
  var source = trafficSource();
  fieldToChange.value = source;
  }

  var trafficSource = function() {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == "utm_source"){
          return pair[1];
      } else if (pair[0] == "gclid") {
          return 'google';
      }
    }
    return 'unknown';
  }


document.onload = addSource();
</script>

Upvotes: 1

Views: 2023

Answers (2)

Sujith Sandeep
Sujith Sandeep

Reputation: 1249

You can take all the query params using new URLSearchParams(window.location.search) and get the particular query param using searchParams.get('utm_source') and then, store the value of utm_source in form field using document.getElementById("utmsource").value = param;.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=\, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="text" id="utmsource" />
    <script>
        let searchParams = new URLSearchParams(window.location.search)
        let param = searchParams.get('utm_source')
        document.getElementById("utmsource").value = param;
    </script>
</body>

</html>

Upvotes: 1

mani-hash
mani-hash

Reputation: 784

fieldToChange is a NodeList so if you want to change the value property you need to specify the index number

So this should fix your code

fieldToChange[0].value = source;

Upvotes: 1

Related Questions