Select default value of <select> element in

2019-08-28 07:48发布

问题:

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>