1

materialize css not working with dynamic select. Its working fine with countries but not showing states.

I think there is some problem with the jquery.

Please check my code snippet.

I have checked everything on the internet. But nothing works for me.

var country_arr = new Array("Afghanistan", "Albania", "Algeria", "American Samoa", "Angola", "Anguilla", "Antartica", "Antigua and Barbuda", "Argentina", "Armenia" );

// 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";
s_a[8]="Barbuda|Redonda|Saint George|Saint John|Saint Mary|Saint Paul|Saint Peter|Saint Philip";
s_a[9]="Antartica e Islas del Atlantico Sur|Buenos Aires|Buenos Aires Capital Federal|Catamarca|Chaco|Chubut|Cordoba|Corrientes|Entre Rios|Formosa|Jujuy|La Pampa|La Rioja|Mendoza|Misiones|Neuquen|Rio Negro|Salta|San Juan|San Luis|Santa Cruz|Santa Fe|Santiago del Estero|Tierra del Fuego|Tucuman";
s_a[10]="Aragatsotn|Ararat|Armavir|Geghark'unik'|Kotayk'|Lorri|Shirak|Syunik'|Tavush|Vayots' Dzor|Yerevan";
// <!-- -->



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('Select State','');
 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]);
 }
  $("#" + stateElementId).material_select();
}

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('Select Country','-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 );
  };
 }
}

populateCountries("country", "state");

$(function () {
    $(document).ready(function () {
        var max_fields = 10; //maximum input boxes allowed
        var wrapper = $("#raghav"); //Fields wrapper
        var add_button = $(".addmore"); //Add button ID

        var x = 1; //initlal text box count
        $(add_button).click(function (e) { //on add input button click
            e.preventDefault();
            if (x < max_fields) { //max input box allowed
                x++; //text box increment
                $(wrapper).append('Select Country: <select id="country'+x+'" name="country" class="country"></select>  Select State: <select id="state'+x+'" name="state" class="state"></select>');
    
                populateCountries("country"+x+"", "state"+x+"");

            }
        });
});

});
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/css/materialize.min.css">
</head>
<body>
<div class="form-group" id="raghav">  
Select Country:<select id="country" name ="country" ></select> 
Select State: <select name ="state" id ="state" class="state"></select> 
</div>  
  
<div class="button-div">
    <input type="button" name="addmore" class="addmore" value="Add More">
    </div>  
  
    

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.6/js/materialize.min.js"></script> 
     <script>
     $(document).ready(function() {
        $('select').material_select();     //select js
    });
  </script>
</body>

1 Answers1

4

material_select(). creates a list ul for select and li for options and then shows this ul as dropdown when you call material_select only country dropdown is filled with data and ul is created for this only so its options are showing.

When you populate the state dropdown ul for this is not created so it doesn't show you need to call material_select when you populate the state dropdown.

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('Select State','');
    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]);
    }
    $("#" + stateElementId).material_select();
}
Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
  • thanks that worked. Thanks for help. Was searching all over the internet for this finally found what i was looking for –  Jun 18 '16 at 17:33
  • Can you do this with adding a add more button. I added a button which clone country and state but the problem is with the help of your code i am only able to show the first instance of list. Rest clones are created but not showing the list. below is my code for add more. –  Jun 19 '16 at 06:51
  • $(function () { $(document).ready(function () { var max_fields = 10; var wrapper = $("#raghav"); //Fields wrapper var add_button = $(".addmore"); //Add button ID var x = 1; //initial text box count $(add_button).click(function (e) { e.preventDefault(); if (x < max_fields) { //max input box allowed x++; //text box increment $(wrapper).append('Select Country: Select State: '); populateCountries("country"+x+"", "state"+x+""); } }); }); }); –  Jun 19 '16 at 06:55
  • Like we did for the state dropdown when a new dropdown is created or after it is filled with data than apply material_select on that. This will solve your issue. – Mairaj Ahmad Jun 19 '16 at 06:56
  • Please take a look i added a add more button in my code snippet.i have tried adding material_select in that dropdown but that doesn't seem to be redering –  Jun 19 '16 at 07:32
  • `$("#"+countryElementId).material_select()` write this line at end of populatecountries method. – Mairaj Ahmad Jun 19 '16 at 07:43
  • I have added my code below and in my code snippet too . Check the last function in my js code –  Jun 19 '16 at 07:44
  • You have added it as answer lol add delete this as you have already added in the question.Try this `$("#"+countryElementId).material_select()` at end of populatecountries method. – Mairaj Ahmad Jun 19 '16 at 07:45
  • i did that but thats not populating state list for the first instance. after clicking add more the states are populating. Please add a code snippet if you have achieved what i am trying to do –  Jun 19 '16 at 07:46
  • Ok thanks problem solved . That worked , i was missing a semicolon . Thanks again –  Jun 19 '16 at 07:47
  • Can you tell me how does materialize creates list of select element, i mean the process and working. Or just provide me with the link. –  Jun 19 '16 at 18:01
  • I have not used this before but you can check its documentation by some google search. – Mairaj Ahmad Jun 20 '16 at 03:10