Hidden Field for H1 Tag

Anonymous
Not applicable

Hidden Field for H1 Tag

We would like to add a hidden field on a form that picks up the H1 tag on the page it is embedded in. How can we do that? Is it possible?
Tags (1)
1 REPLY 1
Anonymous
Not applicable

Re: Hidden Field for H1 Tag

Hi Casey,

Interesting question.

This is certainly possible using Javascript and the Forms 2.0 API. However, it requires writing custom code, so I would really advise you seek the help of a web developer to make sure your specific situation is addressed.

That being said, this is a pretty straightforward operation, and I'd be lying if I said I couldn't tell you how to do it. I have included a sample <script> block below that can be added to the page on which the form is embedded. This script will go fetch the text value of the very first <h1> element on the page, and write it to the hidden field on the form.

This is a simplistic example; if there is more than one <h1> on the page, this blindly grabs the first one. If there are multiple Marketo forms on the page, it attempts to do this with each and every one. As I mentioned above, making this a robust solution that fits your use-case takes more work than I have invested in this response.

This script block must be dropped on the page after the form embed code. You also must replace <hidden_field_name> with the correct value for the name of the hidden field on the form. A list of API names for fields can be exported from Admin -> Field Management.

<script>
// when each Marketo form is initialized...
MktoForms2.whenReady(function(form) {
    // grabs the text value of the very first H1 element
    var h1Text = document.getElementsByTagName("h1")[0].innerText;
    // sets the value of the hidden field to the text value of the H1
    // REPLACE VALUE ON NEXT LINE
    form.setValues({ "<hidden_field_name>" : h1Text });
});
</script>

Best,
Kyle