1

I have two dropdowns and I'm trying to populate the second one using Javascript when the first one changes. It should be populated from the database values contained in 'departements' variable of my views.py file.

I found some code on the web but it didn't work when I tried to apply it to my case. I have next to 0 knowledge in Javascript, so no idea if I'm even on the right path.

Below are more details about my files:

models.py

class data_immo(models.Model):
    id = models.AutoField(primary_key=True)
    insee_dep = models.IntegerField(db_column='INSEE_DEP', blank=True, null=True) 
    nom_reg = models.TextField(db_column='NOM_REG', blank=True, null=True)  

    class Meta:
        managed = True
        db_table = 'immo'

views.py

def MyView(request):

    query_results = data_immo.objects.all()
    regions = data_immo.objects.values_list("nom_reg", flat=True).distinct()
    departements = data_immo.objects.values_list("insee_dep", flat=True).distinct()

    query_results_dict = {
        'query_results': query_results,
        'regions': regions,
        'departements': departements,
    }

    return render(request,'home.html', query_results_dict)

home.html

<select id="reg" name="reg" onChange="populate2()"> 
 {% for item in regions %}
 <option val="{{ item.nom_reg }}"> {{ item.nom_reg }} </option>    
 {% endfor %}
</select>

<select id="dep" name="dep"></select>

<script type="text/javascript">
 function populate2(){      
 $('.dep').append('<option>' + departements[0].insee_dep  + '</option');
      }
</script>

I need the populate2() function to update the 'dep' dropdown. The function is obviously wrong, but I don't know where exactly. Thanks in advance!

2
  • Are you trying to add every value in departements to the <select>? Commented Mar 5, 2020 at 15:12
  • The idea is to first test my Javascript code and see if I can manage to make it work. But the next step will be to add some kind of filter based on the first dropdown selection. Commented Mar 5, 2020 at 15:35

1 Answer 1

1

(DISCLAIMER: It's been a while since I last used Django)

Some things I notice are:

  1. You're querying the element as .dep rather than #dep. . queries the class attribute of the HTML element, and # queries its id.

  2. The closing tag for the options (</option>) has a typo

  3. departements exists only on the server side. You can't use it as a variable directly from javascript.

If I'm understanding your question right, you might want something like the following, if using browser APIs

function populate2() {
    let depSelect = document.querySelector('#dep');
    let option;
    {% for d in departements %}
    option = document.createElement("OPTION");
    option.innerText = "{{ d.insee_dep }}";
    option.value = "{{ d.insee_dep }}";
    depSelect.appendChild(option);
    {% endfor %}
}

or in jQuery

function populate2() {
    let depSelect = $('#dep');
    {% for d in departements %}
    $($.parseHTML('<option></option>'))
        .text("{{ d.insee_dep }}")
        .val("{{ d.insee_dep }}")
        .appendTo(depSelect);
    {% endfor %}
}
Sign up to request clarification or add additional context in comments.

4 Comments

Unfortunately it doesn't work. The "dep" dropdown remains empty.
It definitely did something, but I'm getting a rather strange behaviour now. My dropdown looks to be filled with empty elements. There is a scroll bar now when I click on the dropdown. It seems to have retrieved the correct number of elements, but all elements are blank. Any idea what could cause this?
I found the issue. Basically, I had to replace {{ d.insee_dep }} by {{ d }}. Thank you for your help!
@curiousIT my bad, haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.