我想在我的Django-Project中将属性"selected“添加到这个选择字段中:
<form id="formselect" method="post">
{% csrf_token %}
<select name="position_select" id="position_select">
<option value="0">all positions</option>
{% for position in position_options %}
<option value="{{ position.id }}"
{% if form.position.value == position.id.0 %} selected{% endif %}>
Position: {{ position.position_order }}
</option>
{% endfor %}
</select>
使用此if方法的结果是,现在在该HTML的输出中,每个选项都被标记为选中。有没有更好的方法来处理for循环中的if语句?
我每次点击都会提交这个表单:
$("#position_select").on("change", function() {
document.getElementById("formselect").submit();
});
发布于 2019-03-03 19:04:45
您可以尝试如下所示:
{% for position in position_options %}
{% if form.position.value == position.id.0 %}
<option value="{{ position.id }}" selected>
{% else %}
<option value="{{ position.id }}" selected>
{% endif %}或者:
<option value="{{ position.id }}" {{ form.position.value == position.id.0 ? "selected" : "" }}>https://stackoverflow.com/questions/54965429
复制相似问题