Search code examples
mysqljinja2webapp2google-cloud-sql

Default option in drop-down menu


I've just inherited a project and need help. Using webapp2/jinja2/mysql(CloudSQL), how would you define the default option of a drop-down menu created by a database?

Example DB output:

SELECT * FROM tblNames;

Name_PK   Name
1         Alice
2         Bob

Example code:

<tr class="contactformblock">
  <td align="right">Name</td>
    <td> 
        <select name="Contact_Name">
        {% for state in stategroup %}
        <option value="{{ name[0] }}">{{ name[1] }}</option>
        {% endfor %}
        </select>               
    </td>
  </tr>

Under current conditions, it goes alphabetically. On the page, I'd rather it default the dropdown to Bob (who isn't at the top of the list).


Solution

  • Do this...

        <select name="Contact_Name">
        {% for state in stategroup %}
        {% if name[1] == 'Bob' %}
        <option value="{{ name[0] }}" selected>{{ name[1] }}</option>
        {% else %}
        <option value="{{ name[0] }}">{{ name[1] }}</option>
        {% endif %}
        {% endfor %}
        </select>    
    

    Hope this helps!