Filter in Dynamic Select / Option

1

var escolas = ["UFSCAR", "USP"];
//var alunos = [];

$(document).ready(function() {
  escolas.forEach(function(item) {
    $('select.lista-escola').append('<option>' + item + '</option>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>Escola:<selectclass="lista-escola" name="escola"></select> 
Aluno: <select class="lista-aluno" name="aluno"></select>

I saw some Questions that deal with the same subject, like this: Select Option with Filters

However, my menu works in a more "dynamic" way, it is "populated" in JS itself. And that left me with more difficulty modeling a solution. How can I make sure that, when the "UFSCAR" option is selected, for example, select of students in the respective school is shown?

    
asked by anonymous 01.04.2018 / 15:28

1 answer

1
$(document).ready(function(){
    escolas.forEach(function(item){
        $('select.lista-escola').append('<option>' + item + '</option>');
    });

    $('select.lista-escola').change(function(){
        var valueSelected = this.value;
        if(valueSelected=="UFRRJ"){
            alunosRural.forEach(function(item){
                $('select.lista-aluno').append('<option>' + item + '</option>');
            });
        }
    });
});

You can use change to recognize when select is changed, and then just add a conditional stream and repeat the same as you had done for select of students,

    
01.04.2018 / 17:48