0

I have a select box which has country values attached to it (United Kingdom UK for example)

My goal is to display a country flag image on the page depending on the option selected

It's not possible to insert the image path in the select options, so I want to be able to extract the last 2 characters of the option value and use them in the resulting image src eg

<img src="/images/countries/IN.png">

for India

Can this be done with js?

I have the following at the moment with jQuery which returns the text value of the selected option, but want achieve this in the image URL.

$(document).ready(function(){
    $("select.country").change(function(){
        var selectedCountry = $(".country option:selected").val();
        document.getElementById("resultDiv").innerHTML = selectedCountry;
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
    <label>Select Country:</label>
    <select class="country">
        <option value="United States US">United States US</option>
        <option value="India IN">India IN</option>
        <option value="United Kingdom UK">United Kingdom UK</option>
    </select>
</form>
<div id="resultDiv"><img src="images/++RESULT++.png"></div>
Wang Liang
  • 4,244
  • 6
  • 22
  • 45
Gary
  • 101
  • 1
  • 10
  • 1
    Why not just have the value of the selected option be the image name itself? – Chris Sep 20 '18 at 18:53
  • Thanks for the quick reply. I've elaborated on my question as I don't think I gave enough detail initially :) – Gary Sep 20 '18 at 19:44
  • Add a `data-img` attribute to each option that contains the path to the image you want to show, then read that (using `$(".country option:selected").data('img')`) and set the `src` of the `img` to that value. – Heretic Monkey Sep 20 '18 at 21:05
  • Possible duplicate of [Change image based on dropdown using javascript.](https://stackoverflow.com/questions/22254608/change-image-based-on-dropdown-using-javascript) – Heretic Monkey Sep 20 '18 at 21:10
  • @Gary - Try this: https://stackoverflow.com/questions/10741899/how-to-select-last-two-characters-of-a-string – Chris Sep 21 '18 at 15:25

2 Answers2

1

I have now managed to solve this issue with the following code. Thanks to all for their help!

$(document).ready(function(){
    $("select#country").change(function(){
        var selectedCountry = $("#country option:selected").val();
        var countryCode = selectedCountry.substring(selectedCountry.length-2, selectedCountry.length);
        $("#CountryFlag").html("<img src=\"/images/countries/" + countryCode + ".GIF\"  /> </object>");
    });
});
Gary
  • 101
  • 1
  • 10
0

You can get the last two characters with .substring()

selectedValue.substring(selectedValue.length-2, selectedValue.length)
Steve Archer
  • 641
  • 4
  • 10