2016-01-08 125 views
0

我是一個新手,試圖通過javascrip做我自己的依賴下拉,我有點卡住了。Django:依賴下拉

我有2個區域,A REGION1B REGION2的ID標識,

我有4個城市,A CITYB CITY其中有1C CITYD CITY一個外鍵有外鍵的2。我注意到,只要它循環,它就會出現B CITYD CITY,它們的外鍵爲12

還有比使用.remove更好的選項,因爲它會永久刪除<options>。 有人能指引我正確的方向嗎?

在此先感謝。

我的HTML

<select id="region" name="region"> 
     <option id = 0 >-----</option> 
     {% for item in region %} 
      <option id = {{ item.id }}>{{ item.name }}</option> 
     {% endfor %} 
</select> 

<select id="city" name="city"> 
     <option id = 0>-----</option> 
     {% for item in city %} 
      <option id = {{ item.reg }}>{{ item.name }}</option> 
     {% endfor %} 
</select> 

和我的腳本

$(document).ready(function() { 
    $("#source").change(function() { 
     var region = $(this); 
     var city = document.getElementById("status") 
     var i = 1; 
     while (i < city.length) { 
      if (city.options[i].val != region.val()){ 
       city.options[i].remove(); 
       i++; 
      } 
     } 
    }); 
}); 

這裏是我的模型

class REGION(models.Model): 
    name = models.CharField(max_length=50) 
    def __unicode__(self): 
     return u'%s' % (self.name) 

class CITY(models.Model): 
    name = models.CharField(max_length=50) 
    reg = models.ForeignKey("REGION") 
    def __unicode__(self): 
     return u'%s' % (self.name) 
+1

你應該在JavaScript中建立一個哈希值,鍵這些值是該地區的城市列表。當你觸發'change'事件時,你可以循環你的數據結構來拉動所有城市,然後用你得到的城市替換城市下拉菜單。 –

回答

0

這是我如何解決我的問題(如果你想用javascript)

首先這裏是我的html

<select id="region" name="region"> 
    <option id = 0 >-----</option> 
    {% for item in region %} 
     <option id = {{ item.id }}>{{ item.name }}</option> 
    {% endfor %} 
</select> 

<select id="city" name="city"> 
    <option id = 0>-----</option> 
</select> 

代替.remove我用.append

我的JavaScript

$("#source").change(function() { 
    el = $(this); 
    var select = document.getElementById("city"); 
    $("#city").val([]); 
    select.length = 0; 
    $("#city").append("<option>-----</option>"); 

    <!--This part deletes all records in preparation for new results--> 


    var reg = [{% for item in city %}"{{ item.reg }}"{% if not forloop.last %},{% endif %}{% endfor %}]; 
    var name = [{% for item in city %}"{{ item.name }}"{% if not forloop.last %},{% endif %}{% endfor %}]; 

    <!--Storing all data in an array--> 

    for(var i = 0; i<reg.length; i++){ 
     if(el.val() == reg[i]){ 
      $("#status").append("<option id = "+ reg[i] +" value = \"" + name[i] + "\">" + name[i] + "</option>"); 
     } 

     } 
}); 

感謝您的回答商王