【问题标题】:Select default value of <select> element in Django在 Django 中选择 <select> 元素的默认值
【发布时间】:2015-08-09 21:09:45
【问题描述】:
我有一个按以下方式创建的下拉菜单:
<select id="ip_addr">
{% for host in hosts %}
<option value="{{ host.ipaddress }}">{{ host.ipaddress }}</option>
{% endfor %}
</select>
我不知道如何设置默认值。通常我只会说类似
<option value="0.0.0.0" selected>0.0.0.0</option>
但由于我使用循环填充此下拉菜单,我不知道如何确保选择了我想要的选项。我确信有一种非常直接的方法可以做到这一点,但我对 HTML/JavaScript/Django 还是很陌生。
【问题讨论】:
标签:
javascript
html
django
html-select
【解决方案1】:
您有 2 个选项,使用 Django 模板的内置功能:
- 如果要将第一台主机设置为默认选择选项
- 如果要将特定主机设置为默认选择选项
以下是两种可能的解决方案:
<select id="ip_addr">
{% for host in hosts %}
<option value="{{ host.ipaddress }}" {% if forloop.first %}selected{% endif %}>{{ host.ipaddress }}</option>
{% endfor %}
</select>
<select id="ip_addr">
{% for host in hosts %}
<option value="{{ host.ipaddress }}" {% if host.ipaddress == '0.0.0.0' %}selected{% endif %}>{{ host.ipaddress }}</option>
{% endfor %}
</select>
注意:fooloop.first 是一个特殊的模板循环变量,在循环的第一次迭代期间为 True。
【解决方案2】:
这里是一个例子来决定select的选择索引。
var obj = document.getElementById("sel");
for(i=0; i<obj.options.length; i++){
if(obj.options[i].value == "b"){
obj.selectedIndex = i;
}
}
<select id="sel">
<option value="a">a</option>
<option value="b">b</option>
</select>
【解决方案3】:
经过多次测试,我发现它希望它会有所帮助:
<select>
{% for priority in priorities %}
{% if actual_priority == priority %}
<option select>{{priority}}</option>
{% else %}
<option>{{priority}}</option>
{% endif %}
{% endfor %}
</select>
有必要从您的视图中发送“actual_priority”和“priorities”