根据 Django 中的事件呈现字典的键值



我在 Django 应用程序的.html文件中有两个下拉列表,即:

<select class="form-control" id="exampleFormControlSelect1">
<option>op1</option>

</select>
<select class="form-control" id="exampleFormControlSelect2">
<option>opt1</option>
</select>

字典是从 Django 视图中呈现的.py.我希望键在第一个下拉列表中显示为选项,每当选择键时,都需要在第二个下拉列表中显示相应的值。我尝试了一些js和jina模板,但没有运气。我该如何实现它? 我尝试了以下js:

function myFunction() {
var dict=[];
dict.push("{{Names}}");
alert(Object.keys(dict));
}

我返回的字典的形式是:

Names={1991:["cat & dog","Mat-bat","task force"],1992:["average life span!","text-user"]}

输出:0 姜戈 views.py:

def home(requests):
return render(requests,'home/index.html',{"Names":getNames()})

你可以使用 Django 的模板渲染来填充第一个下拉列表,如下所示:

<select class="form-control" id="exampleFormControlSelect1">
{% for key, values in yourdict %}
<option value={{ values }}>{{ key }}</option>
{% endfor %}
</select>

确保将字典变量传递给模板,并将"yourdict"替换为字典变量的名称。

然后,您需要使用javascript/jquery来填充第二个下拉列表。将 onchange 函数添加到您的第一个下拉列表中:

<select class="form-control" id="exampleFormControlSelect1" onchange="populateSecond()"></select>

然后在JS中你可以定义这个函数:

function populateSecond() {
var select1 = document.getElementById("exampleFormControlSelect1");       
var select2 = document.getElementById("exampleFormControlSelect2");       
var selectedValue = select1.options[select1.selectedIndex].value;
selectedValue.forEach(function(element){       
select2.appendChild(element);  
}     
}

这要求将第一个下拉列表中存储的值识别为数组。我不确定它们是否会随手而来,但如果不是,您可能必须使用 split(( 方法将 selectedValue 的值从字符串转换为数组

最新更新