Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default value for select html element in Jinja template?

Tags:

I'm using flask/jinja in order to make a simple web application. I have a table of records which is taken from a db table, and is called by a webpage which loads the list of records. On each row there is a dropdown list (done using the select HTML tag) on a column.

I realize the below code doesn't do what its supposed to, currently the last option (fourth) is automatically selected because of the selected tag. I've left it in to try show what I'm trying to implement.

Ideally I'd want it to check the current record's status (rec.status in the code below) and depending on that, select the appropriate item in the dropdown.

HTML:

     <tbody>             {% for rec in records %}         <tr>           <td>{{ rec.task }}</td>           <td>             <select>               <option value ="zero" selected={{rec.status==0}}>Zero</option>               <option value ="first" selected={{rec.status==1}}>First</option>               <option value ="second" selected={{rec.status==2}}>Second</option>               <option value ="third" selected={{rec.status==3}}>Third</option>             </select>           </td>           <td><a href={{ "/update_status/"~rec.id}}>Update</a></td>       </tr>       {% endfor %}       </tbody> 

Thanks!

like image 338
Rohan Avatar asked Apr 04 '15 20:04

Rohan


People also ask

How do I select default value in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option.

What is Jinja in HTML?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


1 Answers

You're on the right track - but currently, you're printing selected in all the options in your select box. You can try something like this to only print selected on the correct option:

    <select>       <option value="zero"{% if rec.status==0 %} selected="selected"{% endif %}>Zero</option>       <option value="first"{% if rec.status==1 %} selected="selected"{% endif %}>First</option>       <option value="second"{% if rec.status==2 %} selected="selected"{% endif %}>Second</option>       <option value="third"{% if rec.status==3 %} selected="selected"{% endif %}>Third</option>     </select> 
like image 66
Matt Healy Avatar answered Nov 04 '22 15:11

Matt Healy