user3408102
user3408102

Reputation: 45

jQuery - change iframe src based on select value

Right now, I am trying to change the iframe src value based on what select is picked. I have multiple selects/iframes, so I need something to work for all instances.

<div class="wrap">
    <select class="changer">
        <option value="http://stackoverflow.com">StackOverflow</option>
        <option value="http://google.com">Google</option>
        <option value="http://yahoo.com">Yahoo</option>
        <option value="http://twitter.com">Twitter.com</option>
    </select>
    <iframe src="http://stackoverflow.com"></iframe>
</div>
<div class="wrap">
    <select class="changer">
        <option value="http://stackoverflow.com">StackOverflow</option>
        <option value="http://google.com">Google</option>
        <option value="http://yahoo.com">Yahoo</option>
        <option value="http://twitter.com">Twitter.com</option>
    </select>
    <iframe src="http://stackoverflow.com"></iframe>
</div>

CSS:

.wrap {
    width:50%;
    float:left;
}
iframe {
    width:100%;
    height:500px;
display:block;
}

jQuery:

$('.changer').change(function () {
    $(this).attr('src', this.value);
});

Upvotes: 2

Views: 1365

Answers (2)

mayabelle
mayabelle

Reputation: 10014

Try this:

$('.changer').change(function () {
    $(this).next().attr('src', this.value);
});

Upvotes: 1

Josh Crozier
Josh Crozier

Reputation: 240968

You were changing the src attribute of the select element rather than the iframe element.

Given the HTML, you could use .next('iframe') in order to change the source of the adjacent iframe element.

EXAMPLE HERE

$('.changer').change(function () {
    $(this).next('iframe').attr('src', this.value);
});

Upvotes: 5

Related Questions