Materialize: Dynamic populating of select not working for materialize css

Created on 16 Apr 2016  路  5Comments  路  Source: Dogfalo/materialize

wel.zip

I have attached my php file which represents the issue that I'm facing when using materialize css and dynamically populating select dropdown using javascript.
The select dropdown doesn't get populated by data appended through javascript.
please help.

Most helpful comment

2 issues... in your code.

  1. s1.value == 'Arsenal' --> s1.value == 1
  2. Put "$('select').material_select();" after your for loop. You need to refresh the list after you're done.

In your example, I don't understand why you do basic javascript instead of using jQuery.

function populate(s1,s2){
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    if(s1.value == 1){
        var optionArray = ["Mikel|John Obi Mikel"];
    } 
    for(var option in optionArray){
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        s2.options.add(newOption);
    }

    $('select').material_select();
}

All 5 comments

2 issues... in your code.

  1. s1.value == 'Arsenal' --> s1.value == 1
  2. Put "$('select').material_select();" after your for loop. You need to refresh the list after you're done.

In your example, I don't understand why you do basic javascript instead of using jQuery.

function populate(s1,s2){
    var s1 = document.getElementById(s1);
    var s2 = document.getElementById(s2);
    s2.innerHTML = "";
    if(s1.value == 1){
        var optionArray = ["Mikel|John Obi Mikel"];
    } 
    for(var option in optionArray){
        var pair = optionArray[option].split("|");
        var newOption = document.createElement("option");
        newOption.value = pair[0];
        newOption.innerHTML = pair[1];
        s2.options.add(newOption);
    }

    $('select').material_select();
}

Yep, @matrix818181 is right, you have to call the material_select() function if it is added dynamically. This is also mentioned in the documentation.

But I'm experiencing a different & very odd problem. I've 5 select's on a bottom sheet modal, The first one let me pick first 5, 2nd one let me pick 3 & rest of them allow only 1 item.

All options shows up but behave like this.

What is going on? no errors on console... Please help

But what to do with the behavior of select closing window every time it updates .

This really helped me @Dogfalo. Thank you so much

Was this page helpful?
0 / 5 - 0 ratings

Related issues

bradley-varol picture bradley-varol  路  3Comments

artur99 picture artur99  路  3Comments

ruslandzhumaev picture ruslandzhumaev  路  3Comments

djensen47 picture djensen47  路  3Comments

cope picture cope  路  3Comments