Issue
Keep getting 'undefined' as returned google tag manager variable.
Description
I am trying to write a custom javascript variable to pull 'data-name' IF the 'data-form-title' returns ""
I have a website I am trying to tag and need to grab the form names. The problem came into play where some of the forms' names come back as "" so I wanted to use IF/Then logic to choose another attribute if the first came back empty.
Form that has proper form title https://www.mcgeetoyotaofclaremont.com/popup-availability
Form that has empty "" form title ('text yourself a link') https://www.mcgeetoyotaofclaremont.com/vehicle-details/new-2020-toyota-yaris-hatchback-le-claremont-nh-id-33375400#
What I've Tried
I've tested both querySelectors and they both work on their own. It's when I try to make the IF condition that I run into issues.
I have also tried var answer = 'Unknown' and then replacing the variable with either formtitle or datatitle, depending on the conditional, so that the script only had 1 return in the function.
For the life of me this seems simple and when I cross-check other examples (such as taking the name out of the function) it seems it should work fine.
Current Code
function() {
var formtitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-form-title'].nodeValue;
var datatitle = document.querySelectorAll('form[data-form-title]')[0].attributes['data-name'].nodeValue;
if (formtitle != ""){
return formtitle;
} else {
return datatitle;
}
}