Reputation: 15
I am using javascript to change my images based on a dropdown menu seen below:
<script type="text/javascript">
$(document).ready(function() {
var pics = [
'/pics/graphForAlbania.png?raw=true',
'/pics/graphForAlgeria.png?raw=true',
'/pics/graphForAngola.png?raw=true'
]
$('#picDD').change(function () {
var val = parseInt($('#picDD').val());
$('img').attr("src",pics[val]);
});
});
</script>
<div class="container">
<img src='/pics/graphForAlbania.png?raw=true'/>
<select id="picDD">
<option value ="0" selected>Albania</option>
<option value ="1">Algeria</option>
<option value ="2">Angola</option>
</select>
</div>
but I also have another image:
<img src="/pics/output-onlinepngtools.png?raw=true"/>
that is earlier on in the code that changes along with the other image every time that the drop down is prompted.
Is there a way to have an image in my html code without it changing with the javascript that I wrote? Would I be able to have the image in something beyond an image tag, or should I change something about the javascript?
Upvotes: 0
Views: 65
Reputation: 15857
There are a few different solutions for this, but they all are based on the same concept:
Referring to the specific image you want to change
The simplest solution is give the image a class and referring to that class instead of img
<script type="text/javascript">
$(document).ready(function() {
var pics = [
'/pics/graphForAlbania.png?raw=true',
'/pics/graphForAlgeria.png?raw=true',
'/pics/graphForAngola.png?raw=true'
]
$('#picDD').change(function() {
var val = parseInt($('#picDD').val());
$('.graph').attr("src", pics[val]);
});
});
</script>
<div class="container">
<img class='graph' src='/pics/graphForAlbania.png?raw=true' />
<select id="picDD">
<option value="0" selected>Albania</option>
<option value="1">Algeria</option>
<option value="2">Angola</option>
</select>
</div>
Upvotes: 1
Reputation: 1604
$('img') matches all images on the page. Give it an id or unique class so you can identify it
<script type="text/javascript">
$(document).ready(function() {
var pics = [
'/pics/graphForAlbania.png?raw=true',
'/pics/graphForAlgeria.png?raw=true',
'/pics/graphForAngola.png?raw=true'
]
$('#picDD').change(function () {
var val = parseInt($('#picDD').val());
$('#pic2change').attr("src",pics[val]);
});
});
</script>
<div class="container">
<img id='pic2change' src='/pics/graphForAlbania.png?raw=true'/>
<select id="picDD">
<option value ="0" selected>Albania</option>
<option value ="1">Algeria</option>
<option value ="2">Angola</option>
</select>
</div>
Upvotes: 0