I'm a newbie and trying to make my own dependent dropdown through javascrip and I'm kind of stuck.
I have 2 regions, A REGION
with the id of 1
and B REGION
with the id of 2
,
I have 4 cities, A CITY
and B CITY
which have a foreign key of 1
and C CITY
and D CITY
have the foreign key of 2
. I have noticed that whenever it loops it leaves B CITY
and D CITY
which have the foreign key of 1
and 2
.
Also is there a better option than using .remove
as it permanently deletes the <options>
. Can someone point me in the right direction?
Thanks in advance.
My 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>
and my script
$(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++;
}
}
});
});
Here is my models
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)
Here is how I solved my problem (if you want to use javascript)
First of all here is my 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>
Instead of .remove
I used .append
My 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>");
}
}
});
Thanks for the Answer Shang Wang
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.