JavaScript UTM parameters array not populating form fields

113 Views Asked by At

I have the below script which takes UTM parameter values from the URL querystring i.e. 'example.com?utm_campaign=testCampaign&utm_source=testSource' and is supposed to populate hidden form fields. However the script doesn't seem to work as the input field values are empty?

locationSearch='example.com?utm_campaign=testCampaign&utm_source=testSource';
function getUtmParams(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(locationSearch);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var utmArray = ['utm_campaign','utm_medium','utm_source','utm_content','utm_term'];

for (var i = 0; i < utmArray.length; i++) {
  console.log("a " + utmArray[i] + " = " + getUtmParams(utmArray[i]));
  if(getUtmParams(utmArray[i])){
document.querySelector("div." + utmArray[i] + " input[type=hidden]").value = getUtmParams(utmArray[i]);
  }
}
<div class="utm_campaign">
<input type="hidden" name="2302121" id="e2922" value="">
</div>

<div class="utm_source">
<input type="hidden" name="2388234" id="d4033" value="">
</div>

The folowing line seems to not populate the input fields as the values remain empty?

document.querySelector("div." + utmArray[i] + " input[type=hidden]").value = getUtmParams(utmArray[i]);

1

There are 1 best solutions below

8
JMP On

Your input fields are still hidden. To see them, you need to change the type attribute.

locationSearch='example.com?utm_campaign=testCampaign&utm_source=testSource';

function getUtmParams(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
    results = regex.exec(locationSearch);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var utmArray = ['utm_campaign','utm_medium','utm_source','utm_content','utm_term'];

for (var i = 0; i < utmArray.length; i++) {
  console.log("a " + utmArray[i] + " = " + getUtmParams(utmArray[i]));
  if(getUtmParams(utmArray[i])){
document.querySelector("div." + utmArray[i] + " input[type=hidden]").value = getUtmParams(utmArray[i]);
document.querySelector("div." + utmArray[i] + " input[type=hidden]").type = 'text';
  }
}
<div class="utm_campaign">
<input type="hidden" name="2302121" id="e2922" value="">
</div>

<div class="utm_source">
<input type="hidden" name="2388234" id="d4033" value="">
</div>