Select country then automatically show country code on next input

4.5k Views Asked by At

I'm trying to add a person's nationality and phone number. So I have a dropdown with country names for nationality and an input box to enter a phone number. When a person choose the nationality (country), the next input Phone should show the country code automatically. So I have to store the person's nationality and also the phone number in the database.

        <div class="form-group">
        <label>Nationality</label>

        <select name="country">
        <option value="">Country...</option>
        <option value="Afghanistan">Afghanistan</option>
        <option value="Albania">Albania</option>
        .
        .
        ETC till
        <option value="Zimbabwe">Zimbabwe</option>
        </select>
       </div>

        <div class="form-group">
        <label for="phone">Phone Number</label><
        <input id="phone" name="phone" placeholder="user's number " required="" type="number">
       </div>

Do I need to store them in a database table and retrieve or is there a easy way to do it?

2

There are 2 best solutions below

0
Nikita TSB On

You can add to your option tag some data and use it with jquery:

<option value="Zimbabwe" data-countrycode="+888">Zimbabwe</option>

and jQuery:

<script>
$( "select[name=country]" ).change(function() {
    $('input#phone').val($('option:selected', this).data('countrycode'));
});
</script>
0
mplungjan On

You can have the value="+nnn" or you can have one object you create the dropdown from or you can ajax the value from the backend. Many many ways to skin that cat. No definitive answer

Here I add a data attribute on the option and can use the value or both

$("#areaCode").on("change", function() {
  $('#dialCode').val($('option:selected', this).data('dialcode'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="areaCode">
  <option value="" data-dialcode="">Please select</option>
  <option value="Austria" data-dialcode="+43">Austria</option>
  <option value="Zimbabwe" data-dialcode="+263">Zimbabwe</option>
</select>

<input type="text" id="dialCode"/>