Skip to main content
December 18, 2014
Question

Hidden Field for H1 Tag

  • December 18, 2014
  • 1 reply
  • 517 views
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?
This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.

1 reply

December 18, 2014

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