Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading