在Django中选择<select>元素的默认值

时间:2015-05-27 16:32:28

标签: javascript html django html-select

我有一个以下列方式创建的下拉菜单: &lt; select id =&#34; ip_addr&#34;&gt;     {%for hosts in hosts%}         &lt; option value =&#34; {{host.ipaddress}}&#34;&gt; {{host.ipaddress}}&lt; / option&gt;     {%endfor%} &LT; /选择&GT; 而且我不知道如何设置默认值。通常我会说些什么 &lt; option value =&#34; 0.0.0.0&#34;选择&GT; 0.0.0.0&LT; /选项&GT; 但由于我用循环填充这个下拉菜单,我不知道如何确保选择我想要的选项。我确信有一种非常直接的方法可以做到这一点,但我仍然是HTML / JavaScript / Django的新手。

2 个答案:

答案 0 :(得分:5)

您有两个选项,使用Django模板内置功能:

  1. 如果要将第一个主机设置为默认选择选项
  2. 如果要将特定主机设置为默认选择选项
  3. 以下是两种可能的解决方案:

    <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>
    

    注意:foorloop.first是一个特殊的模板循环变量,在循环的第一次迭代中为True。

答案 1 :(得分:0)

以下是确定所选选择索引的示例。

&#13;
&#13;
var obj = document.getElementById("sel");
for(i=0; i<obj.options.length; i++){
    if(obj.options[i].value == "b"){
        obj.selectedIndex = i;
    }
}
&#13;
<select id="sel">
    <option value="a">a</option>
    <option value="b">b</option>
</select>
&#13;
&#13;
&#13;