1

I have been collecting UTM parameters and using the values to populate form fields successfully for some time. Instead of defaulting to a blank or null value if my utm_source is blank, I would like to provide a default value for utm_source of "website"

Here's my code:

// Parse the URL
function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
  var results = regex.exec(location.search);
  return results === null
    ? ""
    : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName("utm_source");
var medium = getParameterByName("utm_medium");
var campaign = getParameterByName("utm_campaign");

// Put the variable names into the hidden fields in the form.
// selector should be "p.YOURFIELDNAME input"
document.querySelector("p.utm_source input").value = source;
document.querySelector("p.utm_medium input").value = medium;
document.querySelector("p.utm_campaign input").value = campaign;

No error messages and the script works as intended. I am simply looking to add a default value in the event one of the parameters is blank. How can I do that?

grooveplex
  • 2,492
  • 4
  • 28
  • 30

1 Answers1

1

you should be able to do it just via conditional assuming your getParameterByName function returns undefined or a similar falsy value when there is nothing found:

var source = getParameterByName('utm_source') || 'my default value';
Aaron Ross
  • 141
  • 1
  • 5
  • Thank you. I have run some tests using the conditional value on and it is still leaving the field values for unknown utms blank. Captures those that are listed but not the empty or missing ones. – Peter Keiller May 17 '19 at 18:43