Dynamic Select/Option filter

Asked

Viewed 475 times

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: <select class="lista-escola" name="escola"></select> 
Aluno: <select class="lista-aluno" name="aluno"></select>

I’ve seen some questions that deal with the same subject, like this one: Select Option with filters

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

  • Can you show where the student data comes from? Do you retrieve this data remotely or are loaded with the page?

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 the change to recognize when the select is changed, and then, just add a conditional stream and repeat the same as you had done for the select of students,

Browser other questions tagged

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