3

I want to create dependent drop-down menus, but I am unsure as to how to best implement the solution. Based on the value selected in the first drop-down menu, I want to populate the subsequent drop-down menus using that value in my query. Despite the work I have already completed, I am not returning any data after selecting a value in the first drop-down menu. Please let me know if there is any other information I may provide to better illustrate my problem.

Models.py

class Location(models.Model):
    city = models.CharField(max_length=50)
    company = models.ForeignKey("company", on_delete=models.PROTECT)

    def __unicode__(self):
        return u'%s' % self.name


class Company(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return u'%s' % self.name

Views.py

def opportunities(request):
    companies = cwObj.get_companies()
    context = {'companies': companies}
    return render(request, 'website/opportunities.html', context)


def new_opportunity(request):
    source = request.GET.get('selected_company')
    result_set = []
    all_locations = []
    string = str(source[1:-1])
    selected_company = cwObj.get_locations(string)
    all_locations = selected_company
    for location in all_locations:
        result_set.append({'location': location})
    return HttpResponse(json.dumps(result_set), mimetype='application/json', content_type='application/json')

Opportunities.html

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://yourjavascript.com/7174319415/script.js"></script>
        <script>
            $(document).ready(function(){
                 $('select#selectcompanies').change(function () {
                     var optionSelected = $(this).find("option:selected");
                     var valueSelected  = optionSelected.val();
                     var source   = optionSelected.text();


                     data = {'selected_company' : source };
                     ajax('/new_opportunity',data,function(result){

                            console.log(result);
                            $("#selectlocations option").remove();
                            for (var i = result.length - 1; i >= 0; i--) {
                                $("#selectlocations").append('<option>'+ result[i].name +'</option>');
                            };


                         });
                 });
            });
        </script>

<div class="field">
            <label class="label">Client Information:</label>
            <div class="select">
                <select name="selectcompanies" id="selectcompanies">
                    <option value="">Company</option>
                    {% for company in companies %}
                    <option value="" name="selected_company">{{ company.name }}</option>}
                    {% endfor %}
                </select>
            </div>
            <div class="select">
                <select name="selectlocations" id="selectlocations">
                    <option>Location</option>
                    {% for location in locations %}
                    <option value="">{{ location }}</option>
                    {% endfor %}
                </select>
            </div>
garmars
  • 129
  • 1
  • 12
  • what happens when you browse manually to `/new_opportunity`? What is `cwObj`? I suspect you are getting some errors. Use Chrome's developer tools to look at the responses you are getting back (or pick your fav browser with similar tools). – AMG Jun 05 '19 at 01:36
  • @AMG when I navigate to "/opportunities/new_opportunity" I am presented with the TypeError: "'NoneType' object is not subscriptable" on this line "string = str(source[1:-1])?". Lastly, cwObj is an object made from the JSON response returned from my RESTful API calls to the database. Thanks! – garmars Jun 05 '19 at 13:54
  • try `/new_opportunity?selected_company=1` or any valid id from your company model. – AMG Jun 05 '19 at 13:56
  • @AMG I fixed my issues with my JSON response, now I see a populated drop-down menu for a particular "selected_company" at "/opportunities/new_opportunity". However, when I select a company in the first drop-down, the second drop-down is not being populated based on the selection. Any thoughts? Thanks! – garmars Jun 05 '19 at 16:09

1 Answers1

0

If you look at your browser's console (hit F12 if you don't know what that is), what gets logged from the console.log(result); command? I suspect you are not iterating over that result correctly to populate your second select.

I don't know for certain, but I think that $("#selectlocations").append('<option>'+ result[i].name +'</option>'); line should use add instead of append and requires a value and option. See Change the options array of a select list but it may be out of date.

This link may also be of some assistance: https://www.electrictoolbox.com/javascript-add-options-html-select/ which suggests the following although I feel there is probably a better way than having to determine the length on each loop.

var myobject = {
    ValueA : 'Text A',
    ValueB : 'Text B',
    ValueC : 'Text C'
};

var select = document.getElementById("example-select");
for(index in myobject) {
    select.options[select.options.length] = new Option(myobject[index], index);
}
AMG
  • 1,606
  • 1
  • 14
  • 25
  • The command console.log returns: ReferenceError: result is not defined. Also, ReferenceError: ajax is not defined for "ajax('/new_opportunity',data,function(result){" – garmars Jun 05 '19 at 16:44
  • a great tutorial to cover this at https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html – AMG Jun 05 '19 at 16:46
  • if ajax is not defined, then you are likely not loading jquery. Read through the tutorial in the comment above this one. It should sort you out. – AMG Jun 05 '19 at 16:47
  • I have been trying to implement the solution by Iman here: https://stackoverflow.com/questions/25706639/django-dependent-select – garmars Jun 05 '19 at 16:47
  • My only question regarding the tutorial is: I am using a third-party database, when defining the models, do I need to define fields for all that exist within the database for a particular object or can I only define those which I will use? For instance, only Company(name) and Location(name, company). Thanks! – garmars Jun 05 '19 at 16:54
  • Hey, could you please take a look at this new post I created? Link: https://stackoverflow.com/questions/56467672/django-how-to-create-a-dependent-dropdown-list I believe I am very close, but I do not believe the value is getting passed to my view. – garmars Jun 05 '19 at 21:02