如何实现具有多个选择的下拉列表并检索所选元素

时间:2014-12-01 10:22:53

标签: javascript jquery python html django

我是django和html的新手,这里我使用django web框架我想创建一个包含多个选项和按钮的下拉列表,点击按钮后我想要检索所选元素

我非常喜欢html和django,请详细解释

提前致谢

2 个答案:

答案 0 :(得分:0)

首先通过上下文传递所有细节,如

def list_view(request):
    templateVar = {}
    templateVar['countryList'] = Country.objects.all()
    return render(request, 'base.html', templateVar)

之后在HTML中

<div class="formField">
    <label><span>Country</span></label>
    <div class="chosenSelect">
        <select style="width:100%;"  class="chosen-select" name="country" id="country" tabindex="1">
            <option value=""></option>
        {% for country in countryList %}
            <option value="{{ country.id }}" {% if country.id == newDataCountry %}  selected="selected" {% endif %}>{{ country.country_name | safe }}</option>
        {% endfor %}
        </select>
     </div>             
</div>

答案 1 :(得分:0)

如果您正在查看级联下拉列表,请参阅此链接以在简单的jquery的帮助下执行所需的任务。

Link

请参阅Arun P Johnny的回答,他还提供Demo

jQuery(function($) {
var locations = {
    'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
    'Spain': ['Barcelona'],
    'Hungary': ['Pecs'],
    'USA': ['Downers Grove'],
    'Mexico': ['Puebla'],
    'South Africa': ['Midrand'],
    'China': ['Beijing'],
    'Russia': ['St. Petersburg'],
}

var $locations = $('#location');
$('#country').change(function () {
    var country = $(this).val(), lcns = locations[country] || [];

    var html = $.map(lcns, function(lcn){
        return '<option value="' + lcn + '">' + lcn + '</option>'
    }).join('');
    $locations.html(html)
});

});