【问题标题】:Get values from HTML only if the checked box is checked (HTML + Python script)仅在选中复选框时从 HTML 获取值(HTML + Python 脚本)
【发布时间】:2021-11-09 11:28:31
【问题描述】:
我有一个带有多个复选框和相关输入值的网页
使用以下代码:
<tr><td><input type=\"checkbox\" id=\"second_checkbox\" name=\"second_checkbox\" value=\"" + Sample_ID + "\"><label for=\""+ Sample_ID + "\">"+ Sample_ID +"</label><br></td><td><select name=\"option\" id=\"option\"><option value=\"\" selected=\"selected\"></option><option value=\"=\">=</option><option value=\"!=\">!=</option><option value=\">\">></option><option value=\">=\">>=</option><option value=\"<\"><</option><option value=\"<=\"><=</option><option value=\"ilike\">contains</option></select></td><td><input type=\"text\" name=\"valore\" placeholder=\"value\"></td></tr>"
我通过使用这个函数得到不同的值:
filtri = request.form.getlist('second_checkbox')
simbolo = request.form.getlist('option')
valori = request.form.getlist('valore')
但数组“valori”获取页面上的所有空值,我只想获取第一个复选框上选中的值。
我该怎么做?
谢谢
【问题讨论】:
标签:
javascript
python
html
jquery
【解决方案1】:
首先,删除 html 中重复的 id 和名称。 html 中的 id 应该是唯一的。使用正确的选择机制,您也不需要它们。
对于客户端(因此,在浏览器中),您可以使用选择器 [type=checkbox]:checked 选择所有选中的复选框。这是minimal reproducable example。
document.addEventListener(`click`, evt => {
console.clear();
const allChecked = document.querySelectorAll(`[type='checkbox']:checked`);
// ^ only checked
if (allChecked.length) {
return allChecked
.forEach(cb => {
const theRow = cb.closest(`tr`);
console.log(`checked row (#${theRow.rowIndex + 1}) text input value: ${
theRow.querySelector(`input[type='text']`).value || `no value`}`);
});
}
return console.log(`none checked (yet)`);
});
<table>
<tr>
<td>
<input type="checkbox" value="123"> 123
</td>
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 1">
</td>
</tr>
<tr>
<td>
<input type="checkbox" value="456"> 456
</td>
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 2">
</td>
</tr>
<tr>
<td><input type="checkbox" value="789"> 789
<td>
selector here
</td>
<td>
<input type="text" placeholder="value" value="row 3">
</td>
</tr>
</table>