javascript - 根据Django中的事件渲染字典的键值
问题描述
我的 Django 应用程序的 .html 文件中有两个下拉列表,即:
<select class="form-control" id="exampleFormControlSelect1">
<option>op1</option>
</select>
<select class="form-control" id="exampleFormControlSelect2">
<option>opt1</option>
</select>
A dictionary is rendered from the Django views.py.I want the keys to be displayed as options in the first dropdown and whenever a key is selected,the corresponding values need to be displayed in the second dropdown.I tried some js and jina Template但没有运气。我怎样才能实现它?我尝试了以下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 Django 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 的值从字符串转换为数组
推荐阅读
- operators - 如何在 Haxe 中使用合并运算符?
- angular - 在新的浏览器窗口中打开时,第一次无法切换角度材质侧导航
- android - Android API 28 通知标题在希伯来语中不粗体
- python - 为什么美丽的汤选择方法返回无?
- javascript - 保存连接到稍后向他们发送消息的套接字
- flutter - 在容器中颤振拟合图像而不拉伸
- python-3.x - 更改输入光标/指针的 X 和 Y 位置
- ios - Popoverview 不以 iPad 旋转为中心
- python - 如何在另一个任务完成后运行而不需要它
- java - 如何在 Ubuntu 中正确安装 Stanford Parser?(没有 nltk)