[Django]-Select default value of <select> element in Django

13๐Ÿ‘

โœ…

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.

๐Ÿ‘คsuselrd

1๐Ÿ‘

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>
๐Ÿ‘คTing Yi Shih

0๐Ÿ‘

I find it out after several tests hope it will help:

<select>
 {% for priority in priorities %}
  {% if actual_priority == priority %}
   <option select>{{priority}}</option>
  {% else %}
   <option>{{priority}}</option>
  {% endif %}
 {% endfor %}
</select>

It will be necessary to send "actual_priority" and "priorities" from your view

๐Ÿ‘คSymna

0๐Ÿ‘

none of the method mentioned worked for me. But as a work around, I had put the default option as a first element, outside for loop

<select name="Customer" id="Customer">
<option value="{{ defaultValue }}" selected >
{{ defaultValue }}
</option>
{% for val in customerlist %}
<option value="{{val}}">{{val}}</option>
{% endfor %}
</select>
๐Ÿ‘คRaghu Vallikkat

Leave a comment