0

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>
1
  • 2
    Have you looked at it in the Element inspector of your browser's developer tools? Is the src set? Do you see the request for the URL in the Network tab? Is it the URL you expect? Do you get the response you expect? Commented May 10, 2016 at 18:47

3 Answers 3

1

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);

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

It may also work without the protocol if you use the leading //
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.