如题,如何保持checkbox的勾选状态
sr_list.html
<div class="container-fluid" style="margin-top:5px;">
<div style="width:60%;">
<form method="get">
<div class="input-group">
<input type="text" name="q" class="form-control" placeholder="输入关键字以搜索数据并分析">
<span class="input-group-btn">
<button class="btn btn-default" type="submit">查询</button>
</span>
</div>
</form>
</div>
<div style="margin-top:10px;overflow-x: scroll;">
<form method="post">
{% csrf_token %}
<table class="table table-bordered">
<thead>
<tr>
<th>
<button class="btn btn-default" style="height:25px;width:50px;">分析</button>
</th>
{% for i in queryset.0.keys %}
<th>{{ i }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for item in queryset %}
<tr id="list">
<td><input type="checkbox" value="{{ item.id }}" onclick="check()" class="chb"></td>
{% for i in item.values %}
<td>{{ i }}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
<div style="color:blue;">**默认显示前50条数据</div>
<div style="color:red;">**若修改表结构后查询不到数据请先前往数据编辑页面添加数据<a href="/sr/edit/">点此前往</a></div>
</form>
</div>
<ul class="pagination">
{{ page_string }}
</ul>
</div>
<script>
function check(){
var num=0;
var len=document.querySelectorAll('.chb');
len.forEach(input=> {
if(input.checked){
input.name = 'b';
}
})
console.log(len)
}
</script>
django后端视图函数
#数据查询
def sr2(request):
search = request.GET.get('q')
ii = list(request.session["info"].values())[0]
name = []
name.append('sr' + str(ii))
kwargs = {
"host": "localhost",
"port": 3306,
"user": "root",
"passwd": "10868325",
"database": "liuxd",
"charset": "utf8",
"cursorclass": pymysql.cursors.DictCursor
}
db = pymysql.connect(**kwargs)
cur = db.cursor()
sql0 = 'select * from ' + name[0] + ' limit 50;'
cur.execute(sql0)
###分析
bd = request.POST.getlist('b')
new_numbers = []
for n in bd:
new_numbers.append(int(n))
if len(bd)==1:
sql00 = "select * from " + name[0] + " where id=" + str(bd[0]) + ";"
cur.execute(sql00)
obj = cur.fetchall()
return render(request, 'sr_list4.html', {"obj":obj})
if len(bd)>=2:
sql11 = "select * from " + name[0] + " where id in" + str(tuple(new_numbers)) + ";"
cur.execute(sql11)
obj = cur.fetchall()
return render(request, 'sr_list4.html', {"obj": obj})
fields = cur.description
head = []
for field in fields:
head.append(field[0])
if search:
sql1 = "select * from " + name[0] + " where concat (" + ",".join(head) + ") like " + "'%"+search+"%'" + ";"
cur.execute(sql1)
queryset = cur.fetchall()
else:
cur.execute(sql0)
queryset = cur.fetchall()
cur.close()
db.close()
#print(queryset) #[{'id': 1, 'insect_name': '稻纵卷叶螟', 'crop': '水稻', 'harm_days': 7}, {'id': 2, 'insect_name': '棉蚜', 'crop': '棉花', 'harm_days': 5}]
#print(type(queryset))
page_object = Pagination(request, queryset)
context = {"queryset": page_object.page_queryset,
"page_string": page_object.html()
}
return render(request, 'sr_list2.html', context)
如有帮助 一定采纳!