Here’s a handy vanilla JS script to get a value from Google Tag Manager (GTM) and update a form input.
/** * Get value from GTM, and update a form input */ ( function () { window.addEventListener( "load", function () { // Check for our form const form = document.querySelector( '.our-form' ); if ( ! form ) return; // Our field to populate const input = '.our-input'; // We need to wait until GA has loaded function checkGaLoaded () { if ( typeof ga === 'function' ) { console.log('Loaded :'+ ga); // Connect to GA ga( 'create', 'UA-xxxxxxxx-x', 'auto' ); // Get the data const all = ga.getAll(); const pc = all[0]; const data = pc['model']['data']['ea']; for ( const [key, value] of Object.entries( data ) ) { if ( key === ':our_key' ) { console.log('Found'); console.log(value); // Update the form value const our_input = document.getElementById( input ); if ( our_input ) { our_input.value = value; } } } } else { console.log('Not loaded'); setTimeout( checkGaLoaded, 500 ); } } checkGaLoaded(); } ); } )();