简体   繁体   中英

Django Javascript integration

I am trying to create a dynamic list(type radio) when one selects an option. I am able to get the values of the list but I am unable to view it on the page.

This is the code: javascript:

$(document).ready(function() {
    $("select[name=city]").change(function() {
        if ($(this).val() == '') {
            $("select[name=term]").html("<option>Select a frequency</option>");
            $("select[name=term]").attr('disabled', true);
        }
        else {
            var url = "/locality/city/" + Number($(this).val());
            console.log(url)

            $.getJSON(url, function(frequency_list) {
                var li = '<ul id="id_term"><li><label><input id="id_term_0" type="radio" value="-1" name="term"></input>None</label></li>'

                for (var i = 0; i < frequency_list.length; i++) {
                    // console.log(frequency_list[i][0],frequency_list[i][0]);
                    var id = "id_term_" + String(i)
                    li += '<li><label><input id='+String(id)+ ' type="radio" value='+frequency_list[i][0]+ ' name="term"></input>'+frequency_list[i][1]+'</label></li>'
                    console.log(li);
                }

                li +='</ul>'
                $("select[name=term]").html(li);
                // $("select[name=term] li:first").attr('selected', 'selected');
                $("select[name=term]").attr('disabled', false);
            });
        }
    });

    $("select[name=term]").change(function(vent) {
        if ($(this).val() == -1) {
            return;
        }
    });
});

forms:

class CityForm(forms.Form):
    city = forms.ModelChoiceField(queryset=City.objects.all().filter(tagged=True))

class FrequencyForm(CityForm):
    """
    Generates a form consisting of a list of trigrams, bigrams and unigrams in ratio 8:8:2
    """

    def __init__(self, *args, **kwargs):
        super(FrequencyForm, self).__init__(*args, **kwargs)
        self.frequency_list = [('-1','None')]
        self.fields['term'] = forms.ChoiceField(choices=self.frequency_list, required=True, widget=forms.RadioSelect())

If your list gets out ok from your getJSON call, the problem is probably when you're trying to inject content that is not <option> in a <select> element. See <select> specs: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/select It says:

Permitted content Zero or more option or optgroup elements.

So this line will most likely not give any result:

$("select[name=term]").html(li);

So either you add afterwards or you create a new non select element to contain you list.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM