如何使用 Flask 访问 table 中每个复选框的值?
How to access the value of each checkbox in a table with Flask?
我有一个 table 由
填充
<button type="submit" name="update" value = company.index style = margin-left:45%>Update</button>
....
{% for product in products%}
<tr {{product .index}}>
<th scope="row">{{ product .productname }}</th>
<td> {{ product .description }} </td>
<td><form method = "POST"> <input type="checkbox" name="checkbox{{product .index}}" value = {{product .index}}{% if product .like == 1 %} checked {% else %} {% endif %}></form>{{product .like}}</td>
{% endfor %}
根据列表 products
中的产品数量填充 table。然后我在 app.py
试图查看是否有任何框被选中(它们都有不同的名称),问题是,如果我有多行被选中,只有第一行是 returns一个值。
app.py
@app.route('/', methods = ['GET', 'POST'])
def index():
....
for key in request.form:
print(key)
return render_template('index.html', products = products)
因此,如果我的列表 products
包含 3 个产品,它们将在 table 中各排在一行,并且旁边都有一个框。但是当我选中所有框并按下更新按钮时,只会打印第一个按钮的名称。如何访问 table?
中所有按钮的值
又是你哈哈
问题是每个产品都有一个表单元素,所以如果您想检查每个项目,您需要用表单元素包装所有这些项目。
另一种选择是使用 javascript,正如我在您的其他问题中提到的那样。那么您可以删除所有表单元素并改用 javascript 函数。
示例:
<form method="POST">
{% for product in products%}
<tr {{product .index}}>
<th scope="row">{{ product .productname }}</th>
<td> {{ product .description }} </td>
<td>
<input type="checkbox" name="checkbox{{product .index}}"
value={{product .index}}{% if product .like == 1 %} checked {% else %} {% endif %}>
{{product .like}}
</td>
{% endfor %}
<button type="submit" name="update" value="company.index" style="margin-left:45%">Update</button>
</form>
我有一个 table 由
填充 <button type="submit" name="update" value = company.index style = margin-left:45%>Update</button>
....
{% for product in products%}
<tr {{product .index}}>
<th scope="row">{{ product .productname }}</th>
<td> {{ product .description }} </td>
<td><form method = "POST"> <input type="checkbox" name="checkbox{{product .index}}" value = {{product .index}}{% if product .like == 1 %} checked {% else %} {% endif %}></form>{{product .like}}</td>
{% endfor %}
根据列表 products
中的产品数量填充 table。然后我在 app.py
试图查看是否有任何框被选中(它们都有不同的名称),问题是,如果我有多行被选中,只有第一行是 returns一个值。
app.py
@app.route('/', methods = ['GET', 'POST'])
def index():
....
for key in request.form:
print(key)
return render_template('index.html', products = products)
因此,如果我的列表 products
包含 3 个产品,它们将在 table 中各排在一行,并且旁边都有一个框。但是当我选中所有框并按下更新按钮时,只会打印第一个按钮的名称。如何访问 table?
又是你哈哈
问题是每个产品都有一个表单元素,所以如果您想检查每个项目,您需要用表单元素包装所有这些项目。
另一种选择是使用 javascript,正如我在您的其他问题中提到的那样。那么您可以删除所有表单元素并改用 javascript 函数。
示例:
<form method="POST">
{% for product in products%}
<tr {{product .index}}>
<th scope="row">{{ product .productname }}</th>
<td> {{ product .description }} </td>
<td>
<input type="checkbox" name="checkbox{{product .index}}"
value={{product .index}}{% if product .like == 1 %} checked {% else %} {% endif %}>
{{product .like}}
</td>
{% endfor %}
<button type="submit" name="update" value="company.index" style="margin-left:45%">Update</button>
</form>