Zach Mandell Zach Mandell - 1 month ago 6
HTML Question

Passing javascript variables into attribute of html object

I cannot figure out how to pass variables (p1,p2,p3) into the 'data-url' attribute of this html object, an embedded typeform. Any advice?

<script type="text/javascript">// <![CDATA[
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
console.log('The value of ' + name + ' is: ' + results[2].replace(/\+/g, " "));
return decodeURIComponent(results[2].replace(/\+/g, "%20"));
}

var p1 = getParameterByName('p1')
var p2 = getParameterByName('p2')
var p3 = getParameterByName('p3')

p1 = p1.replace(/ /g, "%20");
p2 = p2.replace(/ /g, "%20");
p3 = p3.replace(/ /g, "%20");

var a = window.getElementsByClassName('typeform-widget');
a.setAttribute('data-url', "https://eatforklore.typeform.com/to/XPDPsx?p1=" +p1);
// ]]></script><!-- Change the width and height values to suit you best -->
<div class="typeform-widget" data-url="https://eatforklore.typeform.com/to/XPDPsx?p1=xxxxx&amp;p2=xxxxx&amp;p3=xxxxx&amp;p4=xxxxx" data-text="Mo. 1 Product Reviews" style="width: 100%; height: 500px;"></div>
<script>// <![CDATA[
(function(){var qs,js,q,s,d=document,gi=d.getElementById,ce=d.createElement,gt=d.getElementsByTagName,id='typef_orm',b='https://s3-eu-west-1.amazonaws.com/share.typeform.com/';if(!gi.call(d,id)){js=ce.call(d,'script');js.id=id;js.src=b+'widget.js';q=gt.call(d,'script')[0];q.parentNode.insertBefore(js,q)}})()
// ]]></script>

Answer

The problem is, the script is running before the div with the class name exists. You need to do this:

    <div class="typeform-widget" data-url="https://eatforklore.typeform.com/to/XPDPsx?p1=xxxxx&amp;p2=xxxxx&amp;p3=xxxxx&amp;p4=xxxxx" data-text="Mo. 1 Product Reviews" style="width: 100%; height: 500px;"></div>
    <script type="text/javascript">
        var a = document.getElementsByTagName('typeform-widget');
        a.setAttribute('data-url', "https://eatforklore.typeform.com/to/XPDPsx?p1=" +p1);
    </script>