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.
You have 2 options, using Django templates built-in features:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With