2016-12-14 87 views
0

我想有兩個下拉框。第二個根據第一個下拉列表中的選擇進行填充。第一個下拉菜單工作正常,但第二個下拉菜單沒有。有人可以幫我弄這個嗎?下拉自舉行爲奇怪

HTML:

<div class="container-fluid"> 
     <div class="row"> 
     <div class="col-sm-2 col-md-2 col-lg-2"> 
      <div class="dropdown" id="villageselector"> 
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Village <span class="caret"></span></button> 
      <ul class="dropdown-menu"> 
      </ul> 
      </div>  
     </div> 
     <div class="col-sm-2 col-md-2 col-lg-2"> 
      <div class="dropdown" id="farmerselector"> 
      <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select Farmer <span class="caret"></span></button> 
      <ul class="dropdown-menu"> 
      </ul> 
      </div> 
     </div>   
     </div> 
    </div> 

JS:

//Populate the first dropdown 
    $.each(villagelist, function() { 
     $('#villageselector ul').append('<li><a data-villagename="'+ this.village+'" data-id = "'+this.id+'">' + this.village + '</a></li>'); 
    }); 

    //Add selector on the first dropdown 
    $('#villageselector a').click(function(){ 
     selectedvillagename = $(this).data().villagename; 

     //Populate the second dropdown, based on the selection on the first dropdown 
     $.each(villagelist, function() { 
      if (this.village === selectedvillagename) { 
      for(i=0; i<this.farmernames.length; i++){ 
       $('#farmerselector ul').append('<li><a data-farmername="'+ this.farmernames[i]+'" data-id = "'+i+'">' + this.farmernames[i] + '</a></li>'); 
      } 
      } 
     }); 
     }); 


     $('#farmerselector a').click(function(){ 
      //the list gets populated, but on selecting one of them, the code never reachers here 
     }); 

回答