Set default value for select html element in Jinja template?
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>
For the future Googlers:
If you're using WTForms and want to set the default selection in Jinja, you might dream that something like this could work:
{{ form.gender(class='form-control', value='male') }}
but it doesn't. Neither does default='male'
nor selected='male'
(at least not for me in Jinja 2.8 and WTForms 2.1).
If you're desperate and don't want to set it in your forms.py and don't mind getting a little hacky, you can do this:
{{ form.gender(class='form-control hacky', value=data['gender']) }}
<script>
var els = document.getElementsByClassName("hacky");
for (i = 0; i < els.length; i++) {
els[i].value = els[i].getAttribute('value');
}
</script>
This sets it on page load using JavaScript and lets you pass the default selection in the SelectField without having to mess with your forms.py. There's probably a better way of doing this in Jinja, but I haven't found it yet.