Spanky
Spanky

Reputation: 709

How do you populate an iframe source with a variable?

I am trying to set my current iframe source with a variable that I created but it doesn't seem to work. I figured that my JavaScript syntax is wrong.

My script is:

            <script type="text/javascript">
              $(document).ready(function(){
                var iframeAttributes = window.location.search; 
                var iframeForm = 'www.test.com/form.html';
                var iframeURL = iframeForm + iframeAttributes; 
                $('.testframe').attr('src', iframeURL);
              });
            </script>

My IFrame code is:

            <iframe id="testframe" src="" width="600" height="586" frameBorder="0">></iframe>

Upvotes: 0

Views: 131

Answers (3)

Bubble Hacker
Bubble Hacker

Reputation: 6723

Use a function so you can apply it to any iframe you want:

function changeIframeSrc(id, source){
      $(id).attr('src', source);
}

Example of usage:

changeIframeSrc("#iframe_tab", "http://google.com"); //Notice you can also pass a class into the function instead of an id

Upvotes: 0

yezzz
yezzz

Reputation: 3020

Include the protocol http: or https:

<script type="text/javascript">
$(document).ready(function(){
    var iframeAttributes = window.location.search; 
    var iframeForm = 'http://www.test.com/form.html';
    var iframeURL = iframeForm + iframeAttributes; 
    $('#testframe').attr('src', iframeURL);
});
</script>

Upvotes: 1

XCS
XCS

Reputation: 28147

Your selector is wrong:

$('.testframe').attr('src', iframeURL);

This tries to find elements with class testframe but you have set the ID in your HTML, not the class.

Use this to select the element with id testIframe:

$('#testframe').attr('src', iframeURL);

Upvotes: 1

Related Questions