Select default value of <select> element in Django

僤鯓⒐⒋嵵緔 提交于 2019-12-24 21:03:39

问题


I have a drop down menu that is created in the following fashion:

<select id="ip_addr">
    {% for host in hosts %}
        <option value="{{ host.ipaddress }}">{{ host.ipaddress }}</option>
    {% endfor %}
</select>

and I don't know how to set the default value. Normally I would just say something like

<option value="0.0.0.0" selected>0.0.0.0</option>

but since I am populating this drop down menu with a loop I don't know how to make sure that the option I want is selected. I'm sure there is a really straight forward way to do this, but I am still pretty new to HTML/JavaScript/Django.


回答1:


You have 2 options, using Django templates built-in features:

  1. If you want to set the first host as the default select option
  2. If you want to set an specific host as the default select option

Here are the 2 possible solutions:

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

Note: foorloop.first is a special template loop variable, that is True during the first iteration of a loop.




回答2:


Here is an example to decide the selected index of 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>


来源:https://stackoverflow.com/questions/30488270/select-default-value-of-select-element-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!