Issue
I have a dropdown list in Bootstrap. How to change img src (<img src="img/website_building.jpg"...) when selecting items in the dropdown list. Is this possible?
<tr>
<td class="bold text-primary">
<div class="dropdown show">
<a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Test
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#">1</a>
<a class="dropdown-item" href="#">2</a>
<a class="dropdown-item" href="#">3</a>
</div>
</div>
</td>
<td class="center-image icon">
<img src="img/website_building.jpg" rel="popover" class="highlight zoom img-thumbnail" width="300" alt="">
</td>
</td>
</tr>
Solution
The simplest way is just to create event listeners for the dropdown items and change the URL based on a dictionary or some other source.
For instance, you can create event listeners for the click
event as such:
$(".dropdown-item").click(function () {
console.log('I clicked', this.innerHTML)
});
The next step is to come up with a way to map each dropdown item to the desired image URL. There are a number of ways you can do that, like using dictionaries in which ids of the items are keys and URLs are values. Below I show you an example using data
attributes.
$(".dropdown-item").click(function() {
const imageURL = $(this).data("image");
$("img").attr("src", imageURL);
});
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
Select any item in the dropdown below to change the image.
<table>
<tr>
<td class="bold text-primary">
<div class="dropdown show">
<a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Test
</a>
<div class="dropdown-menu" aria-labelledby="dropdownMenuLink">
<a class="dropdown-item" href="#" data-image="http://bc.id.au/images/it_flag.gif">1</a>
<a class="dropdown-item" href="#" data-image="http://bc.id.au/images/fr_flag.gif">2</a>
<a class="dropdown-item" href="#" data-image="http://bc.id.au/images/es_flag.gif">3</a>
</div>
</div>
</td>
<td class="center-image icon">
<img src="http://bc.id.au/images/de_flag.gif" rel="popover" class="highlight zoom img-thumbnail" width="300" alt="">
</td>
</td>
</tr>
</table>
Answered By - acdcjunior Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.