Creating dynamic dropdown options based off dropdown selection - stuck

女生的网名这么多〃 提交于 2019-12-25 03:13:01

问题


So I am trying to create a dynamic form where the 2nd dropdown box is populated based on the first dropdown.

I am using ajax & jquery to help build this dynamic form in my django project, and I need a bit of help. I have got the ajax call to work properly, and I have sent my choices back to the form, but now I am having trouble populating the form with my choices.

Can someone help me make the json output turn into html options?

Here is my ajax.py:

def switch_plan(request, *args, **kwargs):
    from plans.models import Plan, OwnershipType, MemberType, PlanMember
    from datetime import datetime
    now = datetime.now()
    json = {}
    data = request.POST
    plan_type = data.get('plan-plan_type')
    print plan_type

    if request.is_ajax():
        if plan_type == '5':
            ownership = OwnershipType.objects.all().exclude(id=3).exclude(id=8).exclude(id=9)
            json['owner_types'] = ownership

    return HttpResponse(simplejson.dumps(json), mimetype='application/json')

My plans.html js code:

<script type="text/javascript">
$(function(){
    $("#id_plan-plan_type").change(function() {
        q = $("form").serialize();

        $.ajax({
            type: "POST",
            url: "{% url plans-switch_plan %}",
            dataType: "json",
            data: q,
            success: function(json) {
                //need help here
            }
        });
    });
});

$("#id_plan-ownership_type") is the select field that I need to add the options to.

Edit My json output is as follows {'owner_types': [<OwnershipType: Corporate/Non-Corporate>, <OwnershipType: Estate>, <OwnershipType: In Trust For>, <OwnershipType: Joint Subscriber>, <OwnershipType: Single Subscriber>, <OwnershipType: Tenants in Common>]}


回答1:


In your success callback:

$.each(json.owner_types, function(i, value){
    var opt = $("<option></option>");
    opt.text(value.name);
    opt.val(value.id);
    $("#id_plan-ownership_type").append(opt);
})

You also need to extract your model data into a JSON-serializable type like a dictionary, something along the lines of:

json["owner_types"] = [{"name": o.name, "id": o.id}
        for o in OwnershipType.objects.all()] # or .filter(...)


来源:https://stackoverflow.com/questions/10214618/creating-dynamic-dropdown-options-based-off-dropdown-selection-stuck

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!