show only country code on selected option

I have a list of country in select optio have country code and country name like:

<select class="form-control" name="phone_code">
    <option value="93">Afghanistan (+93)</option>
    <option value="358-18">Aland Islands (+358-18)</option>
    <option value="355">Albania (+355)</option>
    <option value="213">Algeria (+213)</option>
</select>

I just want that, when I select any option, it will show only country code without country name.

How can I achieve this, please help me out.

>Solution :

You can achieve this using Javascript or jQuery. Below is the working solution using jQuery

$(document).ready(function() {
    let defaultOptions = $("#phone_code").html(); // Store the default options HTML
    $("#phone_code").change(function() {
        let countryCode = $(this).val();
        $(this).find("option:selected").text('+' + countryCode);
    }).mousedown(function() {
        // Restore the default options in HTML
        $(this).html(defaultOptions);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" name="phone_code" id="phone_code">
    <option value="93">Select</option>
    <option value="93">Afghanistan (+93)</option>
    <option value="358-18">Aland Islands (+358-18)</option>
    <option value="355">Albania (+355)</option>
    <option value="213">Algeria (+213)</option>
</select>

Leave a Reply