Select the country and bring the state

Asked

Viewed 790 times

1

I have a code that’s on Codeigniter. He has the page to register a user. This page asks him to put the country and the state he lives. I needed it when selecting a country to come the corresponding states that country. I found a Javascript file that serves to do this. In the test I did it worked perfectly, but at the time of putting in my code it does not bring the list of countries that are within the array.

The Javascript file is this:

// Countries
var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa", "Angola", "Anguilla", "Antartica");

// States
var s_a = new Array();
s_a[0]="";
s_a[1]="Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
s_a[2]="Berat|Bulqize|Delvine|Devoll (Bilisht)|Diber (Peshkopi)|Durres|Elbasan|Fier|Gjirokaster|Gramsh|Has (Krume)|Kavaje|Kolonje (Erseke)|Korce|Kruje|Kucove|Kukes|Kurbin|Lezhe|Librazhd|Lushnje|Malesi e Madhe (Koplik)|Mallakaster (Ballsh)|Mat (Burrel)|Mirdite (Rreshen)|Peqin|Permet|Pogradec|Puke|Sarande|Shkoder|Skrapar (Corovode)|Tepelene|Tirane (Tirana)|Tirane (Tirana)|Tropoje (Bajram Curri)|Vlore";
s_a[3]="Adrar|Ain Defla|Ain Temouchent|Alger|Annaba|Batna|Bechar|Bejaia|Biskra|Blida|Bordj Bou Arreridj|Bouira|Boumerdes|Chlef|Constantine|Djelfa|El Bayadh|El Oued|El Tarf|Ghardaia|Guelma|Illizi|Jijel|Khenchela|Laghouat|M'Sila|Mascara|Medea|Mila|Mostaganem|Naama|Oran|Ouargla|Oum el Bouaghi|Relizane|Saida|Setif|Sidi Bel Abbes|Skikda|Souk Ahras|Tamanghasset|Tebessa|Tiaret|Tindouf|Tipaza|Tissemsilt|Tizi Ouzou|Tlemcen";
s_a[4]="Eastern|Manu'a|Rose Island|Swains Island|Western";
s_a[5]="Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire";
s_a[6]="Anguilla";
s_a[7]="Antartica";



function populateStates( countryElementId, stateElementId ){

    var selectedCountryIndex = document.getElementById( countryElementId ).selectedIndex;

    var stateElement = document.getElementById( stateElementId );

    stateElement.length=0;  // Fixed by Julian Woods
    stateElement.options[0] = new Option('Selecione seu estado','');
    stateElement.selectedIndex = 0;

    var state_arr = s_a[selectedCountryIndex].split("|");

    for (var i=0; i<state_arr.length; i++) {
        stateElement.options[stateElement.length] = new Option(state_arr[i],state_arr[i]);
    }
}

function populateCountries(countryElementId, stateElementId){
    // given the id of the <select> tag as function argument, it inserts <option> tags
    var countryElement = document.getElementById(countryElementId);
    countryElement.length=0;
    countryElement.options[0] = new Option('Selecione seu país','-1');
    countryElement.selectedIndex = 0;
    for (var i=0; i<country_arr.length; i++) {
        countryElement.options[countryElement.length] = new Option(country_arr[i],country_arr[i]);
    }

    // Assigned all countries. Now assign event listener for the states.

    if( stateElementId ){
        countryElement.onchange = function(){
            populateStates( countryElementId, stateElementId );
        };
    }
}

My HTML is like this:

<session>
       <label class="select">
              <select id="country" name="country">
                     <option disabled="disabled" selected="selected">país</option>
              </select>
       </label>
</session>

On the test page I put this function:

<script language="javascript">
    populateCountries("country", "state");
</script>

But by putting on my page speech that is not defined.

  • Made the javascript include containing its functions?

2 answers

1


We’re missing a select to receive the cities.

See that in the way populateCountries you pass the city and state id.

Add the HTML:

<select id="state" name="state">
 <option disabled="disabled" selected="selected">Selecione o estado</option>
</select>

See working.

// Countries
var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa", "Angola", "Anguilla", "Antartica");

// States
var s_a = new Array();
s_a[0] = "";
s_a[1] = "Badakhshan|Badghis|Baghlan|Balkh|Bamian|Farah|Faryab|Ghazni|Ghowr|Helmand|Herat|Jowzjan|Kabol|Kandahar|Kapisa|Konar|Kondoz|Laghman|Lowgar|Nangarhar|Nimruz|Oruzgan|Paktia|Paktika|Parvan|Samangan|Sar-e Pol|Takhar|Vardak|Zabol";
s_a[2] = "Berat|Bulqize|Delvine|Devoll (Bilisht)|Diber (Peshkopi)|Durres|Elbasan|Fier|Gjirokaster|Gramsh|Has (Krume)|Kavaje|Kolonje (Erseke)|Korce|Kruje|Kucove|Kukes|Kurbin|Lezhe|Librazhd|Lushnje|Malesi e Madhe (Koplik)|Mallakaster (Ballsh)|Mat (Burrel)|Mirdite (Rreshen)|Peqin|Permet|Pogradec|Puke|Sarande|Shkoder|Skrapar (Corovode)|Tepelene|Tirane (Tirana)|Tirane (Tirana)|Tropoje (Bajram Curri)|Vlore";
s_a[3] = "Adrar|Ain Defla|Ain Temouchent|Alger|Annaba|Batna|Bechar|Bejaia|Biskra|Blida|Bordj Bou Arreridj|Bouira|Boumerdes|Chlef|Constantine|Djelfa|El Bayadh|El Oued|El Tarf|Ghardaia|Guelma|Illizi|Jijel|Khenchela|Laghouat|M'Sila|Mascara|Medea|Mila|Mostaganem|Naama|Oran|Ouargla|Oum el Bouaghi|Relizane|Saida|Setif|Sidi Bel Abbes|Skikda|Souk Ahras|Tamanghasset|Tebessa|Tiaret|Tindouf|Tipaza|Tissemsilt|Tizi Ouzou|Tlemcen";
s_a[4] = "Eastern|Manu'a|Rose Island|Swains Island|Western";
s_a[5] = "Andorra la Vella|Bengo|Benguela|Bie|Cabinda|Canillo|Cuando Cubango|Cuanza Norte|Cuanza Sul|Cunene|Encamp|Escaldes-Engordany|Huambo|Huila|La Massana|Luanda|Lunda Norte|Lunda Sul|Malanje|Moxico|Namibe|Ordino|Sant Julia de Loria|Uige|Zaire";
s_a[6] = "Anguilla";
s_a[7] = "Antartica";

populateCountries("country", "state");




function populateStates(countryElementId, stateElementId) {



    var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;

    var stateElement = document.getElementById(stateElementId);

    stateElement.length = 0; // Fixed by Julian Woods
    stateElement.options[0] = new Option('Selecione seu estado', '');
    stateElement.selectedIndex = 0;

    var state_arr = s_a[selectedCountryIndex].split("|");

    for (var i = 0; i < state_arr.length; i++) {
        stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
    }
}

function populateCountries(countryElementId, stateElementId) {
    // given the id of the <select> tag as function argument, it inserts <option> tags
    var countryElement = document.getElementById(countryElementId);
    countryElement.length = 0;
    countryElement.options[0] = new Option('Selecione seu país', '-1');
    countryElement.selectedIndex = 0;
    for (var i = 0; i < country_arr.length; i++) {
        countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
    }

    // Assigned all countries. Now assign event listener for the states.

    if (stateElementId) {
        countryElement.onchange = function() {
            populateStates(countryElementId, stateElementId);
        };
    }
}
<label class="select">
   <select id="country" name="country">
      <option disabled="disabled" selected="selected">país</option>
   </select>
   <select id="state" name="state">
      <option disabled="disabled" selected="selected">Selecione o estado</option>
   </select>
</label>

  • With these changes worked right. Only when you open for the first time it still doesn’t appear, but when you reload it appears

  • @Ketlin yes, it’s because you haven’t selected any parents yet.

  • Not in the states and in the countries it happened, but I was able to solve it. Thank you!

  • @Ketlin glad you made it, success there.

0

The function populateCountries requires two elements select to generate the code you want.

So the only adjustment you should make is to change your HTML.

<select name="country" id="country"></select>
<select name="state" id="state"></select>

And no js:

populateCountries('country', 'state');

Whether working

  • I forgot to put, but in another <label> I had the select for the state. My code is not even showing the names of the countries to choose.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.