我有多个选择,我在每个循环中有来自mongodb的数据:
<div class="form-group">
<select name="electoralUnit" multiple class="form-control" size="40">
{{#each electoralUnits}}
<option id="electoralUnit" value="{{id}}" onclick="showDiv(this)">{{name}}</option>
{{/each}}
</select>
</div>
我有一张桌子,我需要保持隐藏,直到从多个选择中选择一些东西:
<table class="table table-striped table-sm table-hover" id="hidden_div" style="display:none;">
<thead>
<tr>
<th scope="col">Hours</th>
<th style="display:none">Electoral Units</th>
<th scope="col">Turnouts</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody>
{{#each voterTurnouts}}
<tr>
<th scope="row">{{turnoutByHour}}</th>
<td style="display:none">{{electoralUnit.name}}</td>
<td>{{voterTurnout}}</td>
<td>{{safeVoter}}</td>
<td><a href="/voterTurnouts/edit/{{id}}" class="btn btn-outline-primary btn-sm">Edit</a></td>
</tr>
{{/each}}
</tbody>
</table>
我试过这个javascript代码:
function showDiv(id) {
if (id.value == id) {
document.getElementById('hidden_div').style.display = "block";
} else {
document.getElementById('hidden_div').style.display = "none";
}
}
如您所见,我将showDiv函数放在选项onclick和hidden_div中的表id中。我的表现在已隐藏但在点击某些内容时不会显示。我想if语句中的id不对。我使用mongoose,因为选项中的id是大括号,我不知道如何在javascript函数中捕获它。有人可以解释一下吗?
答案 0 :(得分:1)
我已经提供了代码示例供您参考,希望它会有所帮助。
function showDiv(select) {
// Get selected options
var options = select && select.options;
var selectedRows = [];
for (var opt of options) {
if (opt.selected) selectedRows.push(opt.value);
}
// Display selected rows
var table = document.getElementById('hidden_div');
var trs = table.querySelectorAll('tr');
var hasOptionSelected = false;
for (var tr of trs) {
if (selectedRows.includes(tr.dataset.row)) {
hasOptionSelected = true;
tr.style.display = "block";
}
else {
tr.style.display = "none";
}
}
table.style.display = (hasOptionSelected)? "block" : "none";
}
<div class="form-group">
<select name="electoralUnit" multiple class="form-control" onChange="showDiv(this)">
<option value="1">First</option>
<option value="2">Second</option>
</select>
</div>
<table class="table table-striped table-sm table-hover" id="hidden_div" style="display:none;">
<thead>
<tr>
<th scope="col">Hours</th>
<th style="display:none">Electoral Units</th>
<th scope="col">Turnouts</th>
<th scope="col">Votes</th>
</tr>
</thead>
<tbody>
<tr data-row='1'>
<th scope="row">{{turnoutByHour1}}</th>
<td style="display:none">{{electoralUnit.name}}</td>
<td>{{voterTurnout}}</td>
<td>{{safeVoter}}</td>
<td><a href="/voterTurnouts/edit/{{id}}" class="btn btn-outline-primary btn-sm">Edit</a></td>
</tr>
<tr data-row='2'>
<th scope="row">{{turnoutByHour2}}</th>
<td style="display:none">{{electoralUnit.name}}</td>
<td>{{voterTurnout}}</td>
<td>{{safeVoter}}</td>
<td><a href="/voterTurnouts/edit/{{id}}" class="btn btn-outline-primary btn-sm">Edit</a></td>
</tr>
</tbody>
</table>