Gary
Gary

Reputation: 101

Returning last 2 characters from selected html option in js

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>

Upvotes: 0

Views: 226

Answers (2)

Gary
Gary

Reputation: 101

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

Upvotes: 1

Steve Archer
Steve Archer

Reputation: 641

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

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

Upvotes: 0

Related Questions