-1

I want the user to choose his/her country from a drop-down list, Then I want to show the country code in a text field in order to allow the user to type his/her number.

This is the country list with the phone number code:

  <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>

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

When user choose Saudi Arabia for example I want the text field to show 966
I thought about making the country code as value in the option

I found this similar case here but I prefer to make it as a second option

Community
  • 1
  • 1
Lana
  • 148
  • 1
  • 3
  • 12

4 Answers4

5

Assuming you are using jQuery:

<select name="country" id="country">
    <option value="">Country...</option>
    <option value="966">Saudi Arabia</option>
</select>

$('#country').change(function () {
    var countryCode = $(this).val();

    if (countryCode) {
        $('#phone').val(countryCode);
    }
});

JSFiddle

0

There are several ways to do it. IMO the easier is to create and populate a JS object containing the name of the country as the index and the country code as value. But tou could also use ajax...

mgaido
  • 2,987
  • 3
  • 17
  • 39
0

You can use jquery's change event listener so every time the select is changed the text in the input will change as well. You can have an array that will have both country names and codes and everytime a change accurs it will get the country code from that array.

Click Here for information regarding the change event.

Click Here for information regarding associative arrays which will help you create the array you can use.

Yousef_Shamshoum
  • 787
  • 3
  • 12
0

@Taylor Burleson. Your code looks good

<select name="country" id="country">
    <option value="">Country...</option>
    <option value="966">Saudi Arabia</option>
</select>

$('#country').change(function () {
    var countryCode = $(this).val();

    if (countryCode) {
        $('#phone').val(countryCode);
    }
});

Lana, you should database feed in all the countries; in the same db table you can mass add country code. When you call the db to grab all the information including the code to the user interface, you should be able to display it using the jquery code above.

unixmiah
  • 3,081
  • 1
  • 12
  • 26