0

I can't figure out what's happening here. When I select the $('#semestre') option, everything works perfectly. Then I select the $('#turma') option and change its value. Everything works. Then, I change the $('#semestre') value again, and everything works. However, when I change again the $('#turma') value, I get the alert twice. And if I do it again, I get three times the alert and so on. What am I missing here?

$(document).ready(function(){
    $('.turma').hide();
    $('#semestre').change(function(){
        if($(this).val() != ''){
            $('.options_turma').remove();
            $('.turma').show();
            $.post('seleciona_turmas.php', {cd_turma: $(this).val()}, function(data){
                var item;
                data = jQuery.parseJSON(data);

                $.each(data.json, function(){
                    item = "<option class='options_turma' value='" + this['codigo'] + "'>" + this['descricao'] + "</option>";
                    $('#turma').append(item);
                });

                $('#turma').change(function(){
                    if($(this).val() != ''){
                        alert("OK");
                    }else{
                        alert('NULL');
                    }
                });
            });
        }else{
            $('#turma').val('');
            $('.turma').hide();
        }
    });
});

I tried to be clear, but it's a confusing question.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
ahmm95
  • 95
  • 1
  • 9

3 Answers3

0

You are binding the change event every time you change the semestre dropdown. Pull the #turma event out of the semestre change event.

Like this

$('#semestre').change(function() {
    //Semestre code
});

$('#turma').change(function(){
    //Turma code
});
Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
0

I think that the .change event on #turma tag must be out of .change event on #semestre tag

ghosty89
  • 86
  • 4
0
$('#turma').on('change', function() {
  // ....
});
iury
  • 118
  • 5
  • How is that different from what OP already has? `.change()` is just a shorthand for `on('change')`. http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click – Venkata Krishna Feb 04 '14 at 17:04