0

I am trying this code to create two dropdowns where the second dropdown depends on the first. But I am unable to populate the second dropdown based on first. This is the post that I am following:

http://www.devinterface.com/blog/2011/02/how-to-implement-two-dropdowns-dependent-on-each-other-using-django-and-jquery/

This is my views.py function:

def createNewLocality(request,newLocality): return render(request, 'locality/createNewLocality.html', {'term': newLocality,'tag': tagList()})

def all_json_models(request, tag): current_tag = Tag.objects.get(pk=tag) parents = Tag.objects.all().filter(parent__lt=current_tag) json_parents = serializers.serialize("json", parents) return HttpResponse(json_parents, content_type="application/javascript")

My createNewLocality.html file:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Create New Locality</title>
    <script src="{{ STATIC_URL }}admin/js/jquery.min.js">
    $(document).ready(
                     function() {
                         $("select#tag").change(function() {
                             if ($(this).val() == 'Z') {
                                 $("select#parent").html("<option>Select a parent</option>");
                                 $("select#parent").attr('disabled', true);
                             }
                             else {
                                 var url = "tag/" + $(this).val() + "/all_json_models";
                                 var tag = $(this).val();
                                 $.getJSON(url, function(parents) {
                                     var options = '<option value="Z">Select a parent</option>';
                                     for (var i = 0; i < parents.length; i++) {
                                        options += '<option value="' + parents[i].pk + '">' + parents[i].fields['name'] + '</option>';
                                     }
                                     $("select#parent").html(options);
                                     $("select#parent option:first").attr('selected', 'selected');
                                     $("select#parent").attr('disabled', false);
                                 });
                             }
                         });


                         $("select#parent").change(function(vent) {
                             if ($(this).val() == -1) {
                                 return;
                             }
                         });
                     });
    </script>
</head>
<body>
    {% if term %}
        <p> Create a new entry in locality table for {{ term }}  </p>
        Enter Tag:
        <form method="get" action="">
            <select name="tag" id="tag">
                <option value="Z">Select a Tag</option>
                {% for entry in tag_list %}
                    <option value="{{ entry.id }}">{{ entry.name }}</option>
                {% endfor %}
            </select>
            <br/>
            <br/>
            Enter Parent:
            <br/>
            <select name="parent" id="parent" disabled="true">
                <option>Select a parent</option>
            </select>
            <br/>
            <br/>
            <input type="submit" value="Submit" />
        </form>
    {% endif %}
</body>
</html>

urls.py

url(r'^createNewLocality/(?P<newLocality>[A-Za-z]+)$',views.createNewLocality),
    url(r'^tag/(?P<tag>[-\w]+)/all_json_models/$', views.all_json_models),
blackmamba
  • 1,952
  • 11
  • 34
  • 59
  • Unrelated to your question, but you should probably bear it in mind: stop using STATIC_URL in templates - use `{% static %}` instead! http://staticfiles.productiondjango.com/blog/stop-using-static-url-in-templates/ – Kristian Glass Apr 05 '15 at 23:26

1 Answers1

0

You can try to do the following: Move your onSelect business logic into a separate method and evaluate it on page load. This way you should achieve the desired effect. I didn't get much deeper into your code, but this should do the trick:

 var onTagChange = function() {
     var selectedTag = $("select#tag option:selected");
     if (selectedTag.val() == 'Z') {
         $("select#parent").html("<option>Select a parent</option>");
         $("select#parent").attr('disabled', true);
     }
     else {
         var url = "tag/" + selectedTag.val() + "/all_json_models";
         var tag = selectedTag.val();
         $.getJSON(url, function(parents) {
             var options = '<option value="Z">Select a parent</option>';
             for (var i = 0; i < parents.length; i++) {
                options += '<option value="' + parents[i].pk + '">' + parents[i].fields['name'] + '</option>';
             }
             $("select#parent").html(options);
             $("select#parent option:first").attr('selected', 'selected');
             $("select#parent").attr('disabled', false);
         });
     }
 }

 $("select#tag").change(onTagChange);
 onTagChange();
Todor
  • 15,307
  • 5
  • 55
  • 62
  • Where should I move it? – blackmamba Apr 05 '15 at 15:57
  • Still doesn't populate the second dropdown. – blackmamba Apr 05 '15 at 16:07
  • Is there a possibility that selecting the first drop down is unable to call the script? – blackmamba Apr 05 '15 at 16:14
  • Is your script actually working when you manually select a tag? If no, then i've misunderstood the question. You should learn how to use tools like [`console.log`](http://stackoverflow.com/questions/4539253/what-is-console-log) in order to debug your JS code and find out where it fails. – Todor Apr 05 '15 at 18:17
  • Yep. When I select the tag it gets populated, only the parent is not getting populated. – blackmamba Apr 05 '15 at 19:04
  • I was looking at the log. The $(this).val() is empty. What can be the issue now? – blackmamba Apr 06 '15 at 06:50
  • There are several options, probably `$(this)` is not what you think it is, inspect what `$(this)` is or use another selector instead of `$(this)`, something like `$("select#tag option:selected")`. I've edited the question. – Todor Apr 06 '15 at 08:05
  • I did console.log($this) I got the output: [select#tag, context: select#tag, jquery: "1.9.1", constructor: function, init: function, selector: ""…] When I used $("select#tag option:selected"), it didn't do anything, infact the console.log inside script didn't get printed. – blackmamba Apr 06 '15 at 08:29