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>

5
  • 1
    Why not just have the value of the selected option be the image name itself? Commented Sep 20, 2018 at 18:53
  • Thanks for the quick reply. I've elaborated on my question as I don't think I gave enough detail initially :) Commented Sep 20, 2018 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. Commented Sep 20, 2018 at 21:05
  • Possible duplicate of Change image based on dropdown using javascript. Commented Sep 20, 2018 at 21:10
  • @Gary - Try this: stackoverflow.com/questions/10741899/… Commented Sep 21, 2018 at 15:25

2 Answers 2

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>");
    });
});

Sign up to request clarification or add additional context in comments.

Comments

0

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

selectedValue.substring(selectedValue.length-2, selectedValue.length)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.