Dja*_*oob 0 html javascript django html-select
我有一个按以下方式创建的下拉菜单:
<select id="ip_addr">
{% for host in hosts %}
<option value="{{ host.ipaddress }}">{{ host.ipaddress }}</option>
{% endfor %}
</select>
Run Code Online (Sandbox Code Playgroud)
而且我不知道如何设置默认值。通常我只会说
<option value="0.0.0.0" selected>0.0.0.0</option>
Run Code Online (Sandbox Code Playgroud)
但是由于我使用循环填充了此下拉菜单,因此我不知道如何确保选择了我想要的选项。我敢肯定有一种非常简单的方法可以做到这一点,但是对于HTML / JavaScript / Django我还是很陌生。
您有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>
Run Code Online (Sandbox Code Playgroud)
注意:foorloop.first是一个特殊的模板循环变量,在循环的第一次迭代期间为True。
| 归档时间: |
|
| 查看次数: |
3659 次 |
| 最近记录: |