Reputation: 8995
I am trying to change my iframe src and reload the iframe with the following code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$('#changeframe').click(function () {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
</script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>
When I click "Change" on the button nothing happens. What I am doing wrong?
Upvotes: 4
Views: 14783
Reputation: 178403
$(function() { ... });
or move it below the html since the button
does not exist when the script runs$(function() {
$('#changeframe').click(function() {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
Using a link - no need for jQuery (same if the button above was submitting a form, target iframename):
<a href="http://stackoverflow.com/" target="declinedframe">Change</a>
<iframe name="declinedframe" id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%"></iframe>
If you MUST use jQuery for the link give it the ID of changeframe use
$(function() {
$('#changeframe').on("click",function(e) {
e.preventDefault(); // cancel the link
$('#declinedframe').attr('src', this.href );
});
});
Upvotes: 0
Reputation: 431
The order does matter.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="button" id="changeframe" value="Change">
<iframe id="declinedframe" class="embed-responsive-item" src="http://forgezilla.com" height="585" width="100%" ></iframe>
// Go Last since changeframe hasn't exist yet.
<script>
$('#changeframe').click(function () {
$('#declinedframe').attr('src', 'http://stackoverflow.com');
});
</script>
Upvotes: 7