Iterate over an array to find tags on a page and stamp a date in associated field

SOLVE
scameron
Participant

Hi there,

 

I'm trying to search a blog post for various tags, and stamp a date in a corresponding hidden field when that tag is found. I've tried capturing the urls of the tags in an array, as well as the name of the date fields in another array and then using a forEach to iterate over the tags.  It isn't working for me, any ideas what I'm doing wrong?

 

Here's what I have so far:

 

<script>
$(window).load(function(){
let tags = ["/topic/mena", "/topic/travel", "/topic/cities"];
let fields = ["interestedinmena2", "interestedintravel", "interestedincities"];
let today = new Date();
let formattedDate = today.toISOString().substr(0, 10);

function myFunction(tags, fields) {
$("a[href*='{tags}']").each(function() {
jQuery("input[name='{fields}']").val(formattedDate);
jQuery("input[name='{fields}']").val(formattedDate).change();
})}

tags.forEach(myFunction)
</script>

0 Upvotes
1 Accepted solution

Accepted Solutions
piersg
Solution
Key Advisor

Ok, so I would get the tags from the topics on the page and check against those (sticking completely with JS instead of getting tags via HubL):

 

 

window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
    let tags = [];
    let fields = ["interestedinmena2", "interestedintravel", "interestedincities"];
    let today = new Date();
    let formattedDate = today.toISOString().substr(0, 10);
    // get the topics from the page and push them to tags array
    var topics = document.getElementsByClassName('topic-link');
    for (i = 0; i < topics.length; i++){
        tags.push(topics[i].href.split('/').pop());
    }
    // loop over each tag
    for (i = 0; i < tags.length; i++) {
      // for each loop of tags, loop over each field
      for (j = 0; j < fields.length; j++) {
        // if the field name includes the topic name change the value of that field to the formatted date
        if (fields[j].includes(tags[i])) {
            $("input[name='"+fields[j]+"']").val(formattedDate).change();
        }
      }
    }
  }
});

 

 

Edit: forgot to change .includes(topic) to .includes(tags[i]), sorry

View solution in original post

9 Replies 9
piersg
Key Advisor

Hi @scameron, if I'm correct in thinking that you want to do is for each tag fill in the corresponding form field with the formatted date (i.e. if the tag is /topic/mena then change the value on input field "interestedinmena2" to the formattedDate value, then you need to do a nested for loop like this:

let tags = ["/topic/mena", "/topic/travel", "/topic/cities"];
let fields = ["interestedinmena2", "interestedintravel", "interestedincities"];
let today = new Date();
let formattedDate = today.toISOString().substr(0, 10);
// loop over each tag
for (i = 0; i < tags.length; i++) {
    // get the topic from the tag as a string
    let topic = tags[i].split('/').pop();
    // for each loop of tags, loop over each field
    for (j = 0; j < fields.length; j++) {
        // if the field name includes the topic name change the value of that field to the formatted date
        if (fields[j].includes(topic)) {
            $("input[name='"+fields[j]+"']").val(formattedDate).change();
        }
    }
}

 

scameron
Participant

Wow that's fantastic thank you! That works when I test it, except for when I add  $(window).load(function(){ in front of it (which I understand I need to use because the form loads after the DOM. Do I need to modify something?

0 Upvotes
piersg
Key Advisor

I would wrap it in the Hubspot onFormReady global event (called after the form has been added to the DOM) to make sure that the form has loaded:

 

window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
    let tags = ["/topic/mena", "/topic/travel", "/topic/cities"];
    let fields = ["interestedinmena2", "interestedintravel", "interestedincities"];
    let today = new Date();
    let formattedDate = today.toISOString().substr(0, 10);
    // loop over each tag
    for (i = 0; i < tags.length; i++) {
      // get the topic from the tag as a string
      let topic = tags[i].split('/').pop();
      // for each loop of tags, loop over each field
      for (j = 0; j < fields.length; j++) {
        // if the field name includes the topic name change the value of that field to the formatted date
        if (fields[j].includes(topic)) {
            $("input[name='"+fields[j]+"']").val(formattedDate).change();
        }
      }
    }
  }
});

 

 

0 Upvotes
scameron
Participant

Ah ok, so that works in that it is posting the dates in the fields now (thanks so much!) but I think maybe I wasn't clear, I only want it to post the date in the field if the that topic tage is found on the page of the blog so for instance, someone submitting the form on this blog post should only post the date to the Cities field:

https://blog.oxfordeconomics.com/content/london-monitor-march-2021

0 Upvotes
piersg
Solution
Key Advisor

Ok, so I would get the tags from the topics on the page and check against those (sticking completely with JS instead of getting tags via HubL):

 

 

window.addEventListener('message', event => {
  if(event.data.type === 'hsFormCallback' && event.data.eventName === 'onFormReady') {
    let tags = [];
    let fields = ["interestedinmena2", "interestedintravel", "interestedincities"];
    let today = new Date();
    let formattedDate = today.toISOString().substr(0, 10);
    // get the topics from the page and push them to tags array
    var topics = document.getElementsByClassName('topic-link');
    for (i = 0; i < topics.length; i++){
        tags.push(topics[i].href.split('/').pop());
    }
    // loop over each tag
    for (i = 0; i < tags.length; i++) {
      // for each loop of tags, loop over each field
      for (j = 0; j < fields.length; j++) {
        // if the field name includes the topic name change the value of that field to the formatted date
        if (fields[j].includes(tags[i])) {
            $("input[name='"+fields[j]+"']").val(formattedDate).change();
        }
      }
    }
  }
});

 

 

Edit: forgot to change .includes(topic) to .includes(tags[i]), sorry

View solution in original post

scameron
Participant

Very clever! Getting very close now, but the first two lines seem to be preventing this from working, I tested it in playcode.io and found if i comment out the top two rows it works, but otherwise doesn't, what might cause that?

0 Upvotes
piersg
Key Advisor

@scameron I would test in Hubspot itself, rather than playcode/codepen as those services often use iframes to show the results of your code, and you can't access an iframe with different origin using JS (I know the HS forms script blocks codepen from using it). The same-origin policy will block scripts trying to access a frame with a different origin.

piersg_0-1617009051065.png

 

I've tested this in Hubspot and it works.

 

Edit: I forgot to change .includes(topic) to .includes(tags[i]) in the code above, sorry

scameron
Participant

Ahh, I see it now, that's awesome, it is working now, thank you SO much for your help! You are a superstar 😄 I figured that because I have some two-word tags, and the Hubspot field names don't allow - only _, that I added on a .replace("-","_") right after the split/pop part, it seems to be working well too 😄 

 

Thanks again!

0 Upvotes
piersg
Key Advisor

@scameron No worries, you're welcome!

0 Upvotes